aspose file tools*
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


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Sorted Set Vs Set" Watch "Sorted Set Vs Set" New topic
Author

Sorted Set Vs Set

Kamlesh Kumar
Greenhorn

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
Greenhorn

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
Greenhorn

Joined: Apr 17, 2006
Posts: 8
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
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Sorted Set Vs Set
 
Similar Threads
key-value pair for multiple threads.
@Override && {@inheritDoc}
best way to delete duplicate
Sets (Universal, Subsets, Union)
methods, instances and arrays - swimming in the ocean of java