Java Treeset

INTRODUCTION TO JAVA TREESET

  • This Java Treeset class implements the Set interface and guarantees that the sorted set will be in ascending element order, sorted according to the natural order of the elements or by the comparator provided at set creation time, depending on which constructor is used.
  • This implementation not synchronized provides guaranteed log(n) time cost for the basic operations (add, remove and contains).
public class TreeSet<E>
extends AbstractSet<E>
implements SortedSet<E>, Cloneable, Serializable
To prevent unsynchronized access to the Set.: SortedSet s = Collections.synchronizedSortedSet(new TreeSet(..));

JAVA TREESET EXAMPLE

Below is a TreeSet Example showing how collections are manipulated using a TreeSet
import java.util.Set;
import java.util.TreeSet;
import java.util.Iterator;

public class TreeSetExample {

 public static void doTreeSetExample() {
 }
 public static void main(String[] args) {
  Set treeSet = new TreeSet();
  // the treeset stores Integer objects into the TreeSet
  for (int i = 0; i &lt; 5; i++) {
   treeSet.add(new Integer(i));
  }
  // Since its a Integer Object Set adding any other elements in the Same
  // set will produce a
  // ClassCastException exception at runtime.
  // treeSet.add("a string");
  System.out.print("The elements of the TreeSet are : ");
  Iterator i = treeSet.iterator();
  while (i.hasNext()) {
   System.out.print(i.next() + "\t");
  }
 }
}
Output
The elements of the TreeSet are : 0 1 2 3 4
Download TreeSetExample.java

No comments:

Post a Comment