1.

Differentiate between HashSet and TreeSet. When would you prefer TreeSet to HashSet?

Answer»

Following are the differences between HashSet and TreeSet:-

  • Internal implementation and speed
    • HashSet: For search, insert, and remove operations, it takes constant time on average. TreeSet is slower than HashSet. A hash table is used to implement HashSet.
    • TreeSet: For search, insert, and delete, TreeSet takes O(Log N), which is higher than HashSet. TreeSet, on the other hand, PRESERVES ordered data. Higher() (Returns the least higher element), floor(), CEILING(), and other operations are also supported. In TreeSet, these operations are likewise O(Log n), and HashSet does not implement them. A Self-Balancing Binary Search Tree is used to implement TreeSet (Red Black Tree). In Java, TreeSet is backed by TreeMap.
  • Way of storing elements 
    The elements of a HashSet are not ordered. In Java, the TreeSet class keeps objects in a Sorted order defined by the Comparable or Comparator methods. By default, TreeSet components are sorted in ascending order. It has a number of methods for dealing with ordered sets, including FIRST(), last(), headSet(), tailSet(), and so on.
  • Allowing Null values 
    Null objects are allowed in HashSet. TreeSet does not allow null objects and throws a NULLPOINTEREXCEPTION. This is because TreeSet compares keys using the compareTo() method, which throws java.lang. NullPointerException.
  • Comparison
    HashSet compares two objects in a Set and detects duplicates using the equals() method. For the same purpose, TreeSet employs the compareTo() method. If equals() and compareTo() are not consistent, that is, if equals() returns true for two equal objects but compareTo() returns zero, the contract of the Set interface will be broken, allowing duplicates in Set implementations like TreeSet.

Following are the cases when TreeSet is preferred to HashSet :

  1. Instead of unique elements, sorted unique elements are required. TreeSet returns a sorted list that is always in ascending order.
  2. The locality of TreeSet is higher than that of HashSet. If two entries are close in order, TreeSet places them in the same data structure and hence in memory, but HashSet scatters the entries over memory regardless of the keys to which they are linked.
  3. To sort the components, TreeSet employs the Red-Black tree method. TreeSet is a fantastic solution if you need to do read/write operations regularly.


Discussion

No Comment Found