Skip to content
Advertisement

Why can’t custom comparator be used with hashSet to check duplicate objects

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?

Advertisement

Answer

HashSet<Mobile> mobileSet = new HashSet(new Mobile().new Comparator())

Let’s enumerate several things which are wrong with that line of code:

  • it is missing the ending semicolon (your “syntax error”);
  • it is missing the generic type parameter (or diamond operator) on new HashSet;
  • it is using a constructor argument of incompatible type with HashSet(Collection<? extends E> coll).

The Javadoc of HashSet explains how a hash set works. It should be very easy to realize it has nothing to do with Comparators.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement