It is true that we need to override equals and hashcode method in our POJO if we are going to use it as a Set. But is we use a Sorted Set with a Comparator, do we still need to override the two methods?
Yes, but that is the case with the Set which I have mentioned. I can use a SortedSet with a Comparator and achieve the same result. Means, i can use the comparator to add only the distinct elements. So can there be any more cases where I may need to override equals and hashcode in this case also?
Kamlesh Kumar
Greenhorn
Joined: Apr 17, 2006
Posts: 8
posted
0
Hi, I got the answer @ the best place - Java Documentation
Regarding the implementation of Comparator with Sorted Set, the following two points from java documentation also indicates that we should implement the equals method.
Note that the ordering maintained by a sorted set (whether or not an explicit comparator is provided) must be consistent with equals if the sorted set is to correctly implement the Set interface.
The ordering imposed by a comparator c on a set of elements S is said to be consistent with equals if and only if c.compare(e1, e2)==0 has the same boolean value as e1.equals(e2) for every e1 and e2 in S.