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?