Sunday 29 July 2012

Get Size of Java TreeSet Example


This example shows how to get the size or number  of elements of a Java TreeSet using size method.


import java.util.TreeSet;

public class GetSizeOfJavaTreeSetExample {

 public static void main(String[] args) {

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

  /**
   * To get the size of TreeSet use int size() method of TreeSet class. It
   * returns the number of elements stored in TreeSet object.
   **/
  System.out.println("Size of TreeSet : " + tSet.size());

  // add elements to TreeSet object
  tSet.add(1);
  tSet.add(2);
  tSet.add(3);

  System.out.println("Size of TreeSet after addition : " + tSet.size());

  // remove one element from TreeSet using remove method
  tSet.remove(1);
  System.out.println("Size of TreeSet after removal : " + tSet.size());
 }
}


The output is:


Size of TreeSet : 0
Size of TreeSet after addition : 3
Size of TreeSet after removal : 2

No comments:

Post a Comment