File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Sorted Set Vs Set Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Sorted Set Vs Set" Watch "Sorted Set Vs Set" New topic

Sorted Set Vs Set

Kamlesh Kumar

Joined: Apr 17, 2006
Posts: 8
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?
chander shivdasani
Ranch Hand

Joined: Oct 09, 2007
Posts: 206

It all depends on you. What level of equality do you want amongst your objects.

For example
Consider a class A with instance variable String str

A a = new A("Hi");
A a1 = new A("Hi");

When you add a and a1 to a set, 2 Objects will be added if equals and hashcode are not overridden because they are two separate Objects.

But if you want these meaningful Objects to be equal, then you need to Override equals and hashcode methods.

Equals, by default checks only for Object references and does not care whether they are meaningfully equal or not.

String class overrides equals and hashcode methods because str and str1 are both same.

String str = new String("Hi");
String str1 = new String("Hi");

Enjoy, Chander
SCJP 5, Oracle Certified PL/SQL Developer
Kamlesh Kumar

Joined: Apr 17, 2006
Posts: 8
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

Joined: Apr 17, 2006
Posts: 8
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, e2)==0 has the same boolean value as e1.equals(e2) for every e1 and e2 in S.

Thanks for replies,
In love with Java
I agree. Here's the link:
subject: Sorted Set Vs Set
It's not a secret anymore!