Upload
bharat-savani
View
42
Download
0
Embed Size (px)
Citation preview
Difference between HashSet<E> and TreeSet<E>
By:Bharat Savani.
1. Ordering of Objects
• HashSet– HashSet is not ordered Collection. It inserts objects
based on mathematical hash function.
• TreeSet– TreeSet sorts the elements in natural order. All
elements inserted into the Set must implement the Comparable interface. If it objects does not implement Comparable Interface then we can supply our own Comparable or Comparator object too.
2. Performance
• HashSet– HashSet takes constant time on add, remove &
contains. HashSet is backed by HashMap(Keys sections of Map is Set).
• TreeSet– TreeSet takes O(log n) times for add, remove &
contains operation.
3. Speed
• HashSet– HashSet outperforms TreeSet because HashSet
provides constant time access.
• TreeSet– TreeSet provides O(log n) time for operations.
Hence HashSet is faster than TreeSet.
4. Methods
• HashSet– HashSet has methods of Set interface.
• TreeSet– TreeSet definitely has rich set of methods than
HashSet. As TreeSet implements NavigableSet<> and NavigableSet<> extends SortedSet<>.
5. Backing Implementations
• HashSet– HashSet has backing implementation of HashMap
• TreeSet– TreeSet has backing implementation of TreeMap.
6. Equals and compareTo
• HashSet– HashSet uses equals() method for comparison
• TreeSet– TreeSet uses compareTo() method for ordering of
Objects.
That’s all folks.