How Treeset checks for duplicates while inserting?
- Treeset uses compareTo() or compare() methods to compare elements.
- If the element you want to insert into treeset implements Comparable interface, then Treeset uses compareTo() method to compare with the elements already present in the set.
- Treeset doesn't use equals() or hashcode() to compare elements.
Some more points about TreeSet:
- The most fundamental behavior of TreeSet is it doesn't allow duplicate entries as it is also a set.
- TreeSet preserves the order of elements in which they are inserted.
- TreeSet uses binary search to locate an item.
- TreeSet is backed by TreeMap.
- TreeSet implements NavigableSet
- If you have not provided Customer comparator and if the user defined element has not implemented Comparable interface, then adding an element throws Runtime error.
Comments
Post a Comment