Sunday, 29 July 2012

Simple Java TreeSet example


This simple Java Example shows how to use Java TreeSet. It also describes how to add something to TreeSet object using add method.


import java.util.TreeSet;

public class SimpleJavaTreeSetExample {

 public static void main(String[] args) {

  // create object of TreeSet
  TreeSet tSet = new TreeSet();

  /**
   * Add an Object to TreeSet using boolean add(Object obj) method of Java
   * TreeSet class. This method adds an element to TreeSet if it is not
   * already present in TreeSet. It returns true if the element was added
   * to TreeSet, false otherwise.
   **/

  System.out.println("Adding 2:" + tSet.add(2));
  System.out.println("Adding 1:" + tSet.add(1));
  System.out.println("Adding 3:" + tSet.add(3));

  /** A set can't occupy duplicate elements, so returns false. **/

  System.out.println("Again adding 1:" + tSet.add(1));

  /**
   * TreeSet class guarantees that the sorted set will be in ascending
   * element order, sorted according to the natural order of the
   * elements;so here prints 1 2 3.
   **/
  System.out.println("TreeSet contains.." + tSet);
 }
}


The output is:



Adding 2:true
Adding 1:true
Adding 3:true
Again adding 1:false
TreeSet contains..[1, 2, 3]

No comments:

Post a Comment