Saturday, 4 February 2017

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:
  1. The most fundamental behavior of TreeSet is it doesn't allow duplicate entries as it is also a set. 
  2. TreeSet preserves the order of elements in which they are inserted.
  3. TreeSet uses binary search to locate an item. 
  4. TreeSet is backed by TreeMap. 
  5. TreeSet implements NavigableSet
  6. 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.  

0 comments:

Post a Comment

Note: only a member of this blog may post a comment.