Java Collection: TreeSet - BunksAllowed

BunksAllowed is an effort to facilitate Self Learning process through the provision of quality tutorials.

Random Posts


The TreeSet is used to store objects in natural ordering or by a provided Comparator.

A few important facts about TreeSet are as follows:

  1. It is not synchronized.
  2. It does not allow duplicate elements.
  3. It does not allow a null key, but values can be null.

Hierarchy of TreeSet class


It inherits methods from AbstractSet and implements Serializable, Clonable, and NavigatableSet interfaces.

Source code of Item.java
package com.t4b.test; public class Item { String name; int id; double price; public Item(String name, int id, double price) { super(); this.name = name; this.id = id; this.price = price; } @Override public String toString() { return "Item [name=" + name + ", id=" + id + ", price=" + price + "]"; } }

Source code of TestMain.java
package com.t4b.test; import java.util.Iterator; import java.util.TreeSet; public class TestMain { public static void main(String[] args) { TreeSet<Item> treeset = new TreeSet<Item>(); treeset.add(new Item("Apple", 1, 150.0)); treeset.add(new Item("Grape", 2, 250.0)); treeset.add(new Item("Mango", 3, 10)); treeset.add(new Item("Pine Apple", 4, 100)); Iterator<Item> itr = treeset.iterator(); while (itr.hasNext()) { System.out.println(itr.next()); } } }

Happy Exploring!

No comments:

Post a Comment