File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes Does equal() not have to be overridden Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of JavaScript Promises Essentials this week in the JavaScript forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Does equal() not have to be overridden" Watch "Does equal() not have to be overridden" New topic
Author

Does equal() not have to be overridden

Jenna Thomas
Greenhorn

Joined: Oct 03, 2005
Posts: 27
Im trying to understand the concept here. I was reading about TreeSets in Kathy Sierras SCJP guide and Im confused. Heres the code sample-

import java.util.*;
class SetTest
{
public static void main(String[] args)
{
boolean [] ba=new boolean[5];
Set<DVDInfo> s=new TreeSet<DVDInfo>();
ba[0]=s.add(new DVDInfo("Donnie Darko", "Sci Fi", "Gyllenhal, Jake"));
ba[1]=s.add(new DVDInfo("Raiders of the Lost Ark", "Action", "Ford, Harrison"));
ba[2]=s.add(new DVDInfo("2001", "Sci Fi", "??"));
ba[3]=s.add(new DVDInfo("Caddy Shack", "comedy", "Murray, Bill"));
ba[4]=s.add(new DVDInfo("Caddy Shack", "comedy", "Murray, Bill"));

for (boolean b :ba )
{
System.out.println(b +" ");
}
System.out.println("\n");

for (DVDInfo o:s)
{
System.out.println(o +" ");
}
}
}

class DVDInfo implements Comparable<DVDInfo>
{
String name;
String genre;
String actor;

DVDInfo(String n, String g, String a){
name=n;
genre=g;
actor=a;
}

public String toString(){
return ("name="+ " "+name+" genre="+genre+" actor="+actor);
}

public int compareTo(DVDInfo d){
return name.compareTo(d.name);
}
}

Ive not overridden equals() or hashCode() here for the DVDInfo class. But the output is this-

true
true
true
true
false


name= 2001 genre=Sci Fi actor=??
name= Caddy Shack genre=comedy actor=Murray, Bill
name= Donnie Darko genre=Sci Fi actor=Gyllenhal, Jake
name= Raiders of the Lost Ark genre=Action actor=Ford, Harrison

Meaning that the meaningfully equivalent second object(ba[4]) I tried to add does not get added to the TreeSet. So, if the comparable() interface is implemented, does this mean that equals() and hashCode() does not have to be overriddden in an object that is going to be added to a TreeSet?


Cheers!
Jenn SCJP1.5
Jenna Thomas
Greenhorn

Joined: Oct 03, 2005
Posts: 27
Ive just noticed that infact if it was a HashSet that I was adding the objects to, the equals() and hashCode() functions would have to be implemented else, meaningfully identical objects are added to hashSets EVEN IF the comparable interface is implemented!

So, I suppose its just best when creating a class equals(), hashCode() and the comparable interface should be implemented! Just in case, we decide to use either the treeset or the hashset? Anyway, why does the Treeset need the comparable interface to be implemented? Wont the equals() suffice?
Steve Luke
Bartender

Joined: Jan 28, 2003
Posts: 4181
    
  21

Originally posted by Jenna Thomas:
Ive just noticed that infact if it was a HashSet that I was adding the objects to, the equals() and hashCode() functions would have to be implemented else, meaningfully identical objects are added to hashSets EVEN IF the comparable interface is implemented!

So, I suppose its just best when creating a class equals(), hashCode() and the comparable interface should be implemented! Just in case, we decide to use either the treeset or the hashset? Anyway, why does the Treeset need the comparable interface to be implemented? Wont the equals() suffice?


TreeSet is a SortedSet, while HashSet is not. The rules for a normal Set is that you can not have equal objects in the Set. Normally equality is determined either by the equals() or the hashCode() method. So if you plan on putting an object into a Set (or as the Key to a Map) the equals() and hashCode() should be overridden in a meaningful manner.

SortedSets, however, also maintain the Order of objects in the Set. The Order is defined by forcing objects in the Set to implement Comparable (or providing a Comparator). So for SortedSets the value returned from compareTo() is used to determine if an object belongs before (negative number), or after (positive number) an element in the Set already, or if the object is equivalent to (zero return value) one in the array.

If you are using the class in a SortedSet like a TreeSet You should still override the equals() and hashCode() methods to allow it to be used in the most versatile manner and to prevent un-expected behavior elsewhere. Just make sure your compareTo() method returns zero anytime equals() returns true (and hashCode() returns the same value).


Steve
Jenna Thomas
Greenhorn

Joined: Oct 03, 2005
Posts: 27
Thanks Steve, your explanation clears out the fog in my head about that. equals() (and its conjoined twin hashcode()) is used to determine equality -so they need to be implemented in hashsets where duplicates are not allowed. A treeset not only disallows duplicates, insertion has to happen in sort order. equals() does not provide enough information to determine the insertion point- only the comparator or comparable interface does that. Makes sense! Just writing it down made it clearer! Thanks again :-)
Mike Simmons
Ranch Hand

Joined: Mar 05, 2008
Posts: 3018
    
  10
[Jenna]: A treeset not only disallows duplicates, insertion has to happen in sort order.

This part is not correct. You can insert items in any order you want, but they will be put into a different order based on the Comparable/Comparator implementation that is used. So you can say

and the output will be

which is alphabetic order, not insertion order.
Jenna Thomas
Greenhorn

Joined: Oct 03, 2005
Posts: 27
Thanks Mike.. I should have phrased the sentence better- In a treeset, insertion happens according to sort order- natural ordering(Alphabetic) if its a String or custom ordering as defined in the comparator/comparable interface.
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19755
    
  20

If you mean with insertion the place where the element will be inserted into the TreeSet then yes, you are right. Like Mike said, the order in which you want to add elements does not matter at all.

Therefore you can better say that the comparator determines the retrieval order, not the insertion order.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Does equal() not have to be overridden