This week's book giveaway is in the OCAJP forum.
We're giving away four copies of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) and have Khalid A Mughal & Rolf W Rasmussen on-line!
See this thread for details.
Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Sorted Set Vs Set

 
Kamlesh Kumar
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 206
Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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");
 
Kamlesh Kumar
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

Thanks for replies,
Kamlesh
In love with Java
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic