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

Why does it give exception

 
rimzy abdulkader
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
import java.util.*;
public class test{
public static void main(String a[]){
Set s = new TreeSet();
s.add(new Person(20));
s.add(new Person(10));
System.out.println(s);
}
}
class Person{
Person(int i){}
}
[ October 04, 2006: Message edited by: rimzy abdulkader ]
 
Ali Gohar
Ranch Hand
Posts: 572
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
TreeSet requires that objects added to it should implements Comparable.

Check this out i have modified your code here

 
Steven Gao Song
Ranch Hand
Posts: 78
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You did not override the equals() and hashCode() methods.

I think you should override them in order to use TreeSet.

Am I right? or it is not necessary?
 
Rajesh Kadle
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
equals() and hashCode() methods should be overridden if we want to store
the objects in HashSet or LinkedHashSet or HashMap or LinkedHashMap.

If you want to store the objects in TreeSet or TreeMap you should can override compareTo() method. This will provide the NATURAL ORDERING.

We can also manage by not implementing 'compareTo()' but passing OUR IMPLEMENTATION of 'Comparator' INTERFACE to the TreeSet/TreeMap constructors. Comparator interface provides 'comparable(Object o1, Object o2) method which should be overridden.

We need not override equals() and hashCode() for TreeSet and TreeMap.

Ranchers please correct me.....
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic