Saturday, August 3, 2019

TreeSet


public class TreeSet<E> extends AbstractSet<E>
 implements NavigableSet<E>, Cloneable, Serializable

public interface NavigableSet<E> extends SortedSet<E>
Type Parameters:
E - the type of elements maintained by this set

All Implemented Interfaces:
Serializable, Cloneable, Iterable<E>, Collection<E>, NavigableSet<E>, Set<E>, SortedSet<E>
  • TreeSet class is implementation of NavigableSet interface and NavigableSet extends SortedSet Interface that means you can say TreeSet is implementation SortedSet.
  • TreeSet internally use TreeMap to store elements.
  • It store key as elements in HashMap and value as PRESENT where  PRESENT = new Object(); 

private static final Object PRESENT = new Object(); 
public boolean add(E e) {
        return m.put(e, PRESENT)==null;
    }

  • TreeSet can not have duplicate elements i.e.it has only unique element only.
  • TreeSet cannot contain null value. if add null values it will throw NullPointerException.
  • The elements are in sorted order using their natural ordering, or by a Comparator provided at creation time, depending on which constructor is used.
  • TreeSet implementation provides guaranteed log(n) time cost for add, remove and contains operations.
  • TreeSet are not thread-safe i.e not synchronized. You can use Collections.synchronizedSet()  method to make them synchronized.

Example to test null value in TreeSet:-

package com.shubh.example;

import java.util.SortedSet;
import java.util.TreeSet;

public class TreeSetExample {
 
 public static void main(String[] args) {
  SortedSet<String> treeSet = new TreeSet<>();
  treeSet.add("Hi Aa");
  treeSet.add(null);
  //treeSet.add(null);
  System.out.println(treeSet);
 }
}
Output:-

Exception in thread "main" java.lang.NullPointerException
 at java.util.TreeMap.put(Unknown Source)
 at java.util.TreeSet.add(Unknown Source)
 at com.shubh.example.TreeSetExample.main(TreeSetExample.java:11)

No comments:

Post a Comment