| Author |
Why does it give exception
|
rimzy abdulkader
Greenhorn
Joined: Oct 04, 2006
Posts: 18
|
|
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 ]
|
SCJP 5.0
|
 |
Ali Gohar
Ranch Hand
Joined: Mar 18, 2004
Posts: 572
|
|
TreeSet requires that objects added to it should implements Comparable. Check this out i have modified your code here
|
 |
Steven Gao Song
Ranch Hand
Joined: Oct 02, 2006
Posts: 78
|
|
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
Joined: Sep 06, 2004
Posts: 26
|
|
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.....
|
-Raj
|
 |
 |
|
|
subject: Why does it give exception
|
|
|