8
Difference between HashSet<E> and TreeSet<E> By: Bharat Savani.

Difference between HashSet and TreeSet

Embed Size (px)

Citation preview

Page 1: Difference between HashSet and TreeSet

Difference between HashSet<E> and TreeSet<E>

By:Bharat Savani.

Page 2: Difference between HashSet and TreeSet

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.

Page 3: Difference between HashSet and TreeSet

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.

Page 4: Difference between HashSet and TreeSet

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.

Page 5: Difference between HashSet and 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<>.

Page 6: Difference between HashSet and TreeSet

5. Backing Implementations

• HashSet– HashSet has backing implementation of HashMap

• TreeSet– TreeSet has backing implementation of TreeMap.

Page 7: Difference between HashSet and TreeSet

6. Equals and compareTo

• HashSet– HashSet uses equals() method for comparison

• TreeSet– TreeSet uses compareTo() method for ordering of

Objects.

Page 8: Difference between HashSet and TreeSet

That’s all folks.