TreeSet Example in Java

About TreeSet:
  • TreeSet is class which extends AbstractSet and Implements NavigableSet Interface
  • It does maintain ascending order
  • It does not allow null
  • Contains unique elements Only, same as HashSet and LinkedHashSet


If You observe output of TreeSet example as below, Output is ascending order and NullPointer Exception will be thrown if You try to add null into TreetSet.

Java TreeSet Example :
package com.anuj.basic;

import java.util.Iterator;
import java.util.TreeSet;

/**
 * 
 * @author Anuj
 * allows unique elements only
 * maintain ascending order
 */
public class TreeSetOperations {

 public static void main(String[] args) {
  TreeSet treeSet = new TreeSet();
  
  treeSet.add("Anuj");
  treeSet.add("Zvika");
  treeSet.add("David");
  treeSet.add("David");
  //treeSet.add(null); //Exception
  
  Iterator iterator = treeSet.iterator();
  while(iterator.hasNext()){
   System.out.println(iterator.next());
  }
 }

}

Output :
Anuj
David
Zvika

//Exception when adding null
Exception in thread "main" java.lang.NullPointerException
at java.util.TreeMap.put(TreeMap.java:556)
at java.util.TreeSet.add(TreeSet.java:255)
at com.anuj.basic.TreeSetOperations.main(TreeSetOperations.java:21)

No comments:

Post a Comment