Issue
I want to use a custom comparator to filter duplicate objects from a HashSet.
In the Mobile class, I have defined a non-static nested Comparator class for comparing. The criterium which is used by this comparator is the id field of the Mobile object.
Set<Mobile> treeSet = new TreeSet<>(new Mobile().new Comparator()); // works
Set<Mobile> hashSet = new HashSet<>(new Mobile().new Comparator()); // does not work
Even though it works perfectly for a TreeSet, Eclipse shows a syntax error when I try this with a HashSet,
It appears that I need to override the equals and hashcode methods in the Mobile class if I want to use a HashSet. However, I would prefer to use a comparator instead.
Why is this the case?
Solution
HashSet is backed by a hashtable, which is an unordered data structure. This is why it has no need for a comparator. On the other hand, TreeSet is backed by a binary search tree (an ordered structure), and so it needs a comparator.
The correctness of a hashtable relies on the equals method, while its performance relies on a well-chosen hashCode. You can read more about it in the Javadoc of HashSet and the Object.hashCode() method itself.
Answered By - Marko Topolnik
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.