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 O(log(n)) time cost for add, remove and contains operations.
- first(), last(), headset(), tailset(), etc. time complexity of basic methods is O(1)
- 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)
Related Tutorials
- Java Collections Interview
- Custom Own ArrayList Implementation
- List Interface In Java
- ArrayList
- LinkedList
- Set Interface In Java
- Map Interface In Java
- HashMap In Java
- HashMap Vs ConcurrentHashMap
- HashMap Vs HashTable In Java
- HashMap Vs HashSet In Java
- HashMap Vs TreeMap In Java
- HashMap vs LinkedHashMap In Java
- TreeSet Vs TreeMap In Java
- SortedSet Vs TreeSet In Java
- SortedMap Vs TreeMap In Java
- Array Vs ArrayList In Java
- ArrayList Vs LinkedList In Java
- How HashSet Works Internally
- How TreeMap Works Internally
- How HashMap Works Internally
- How ConcurrentHashMap Works Internally
No comments:
Post a Comment