TreeSet
elements are sorted according to their natural ordere if created using
default constructor( new TreeSet()), or by a Comparator if TreeSet
object is created by passing Comparator to constructor ( new
TreeSet(comparator))
· If TreeSet object is created using default constructor then all elements inserted into the set must implement the Comparable interface else you will get exception while adding elements to TreeSet instance.
java.lang.ClassCastException: xxxx cannot be cast to java.lang.Comparable
· All elements inserted into the set must be of same type. e.g. you can not add String into a set whose elements are Integers
· provides guaranteed log(n) time cost for the contains, add and remove operations.
· Does not allows null element. If null element is added then it will throw NullPointerException at runtime. Whereas, hashset allows one null value
· A TreeSet is not synchronized. Means it's methods are not synchronized.
· In multi-threaded environment, to prevent accidental unsynchronized access to the TreeSet to a thread that can modify this set, wrap TreeMap instance using Collections. synchronizedSortedSet method
SortedMap m = Collections. synchronizedSortedSet(new TreeSet(...));
· The iterators returned by this class's iterator methods are fail-fast. If the set is modified at any time after the iterator is created, in any way except through the iterator's own remove method, the iterator will throw a ConcurrentModificationExceptio n.
· Fail-fast iterators throw ConcurrentModificationExceptio n on a best-effort basis. But one must not write program that depends on this behaviour.
· add(E e) method returns false if set already contains the element e
· If TreeSet object is created using default constructor then all elements inserted into the set must implement the Comparable interface else you will get exception while adding elements to TreeSet instance.
java.lang.ClassCastException: xxxx cannot be cast to java.lang.Comparable
· All elements inserted into the set must be of same type. e.g. you can not add String into a set whose elements are Integers
· provides guaranteed log(n) time cost for the contains, add and remove operations.
· Does not allows null element. If null element is added then it will throw NullPointerException at runtime. Whereas, hashset allows one null value
· A TreeSet is not synchronized. Means it's methods are not synchronized.
· In multi-threaded environment, to prevent accidental unsynchronized access to the TreeSet to a thread that can modify this set, wrap TreeMap instance using Collections.
SortedMap m = Collections.
· The iterators returned by this class's iterator methods are fail-fast. If the set is modified at any time after the iterator is created, in any way except through the iterator's own remove method, the iterator will throw a ConcurrentModificationExceptio
· Fail-fast iterators throw ConcurrentModificationExceptio
· add(E e) method returns false if set already contains the element e