File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Why does it give exception Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Why does it give exception" Watch "Why does it give exception" New topic

Why does it give exception

rimzy abdulkader

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));
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

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.....

With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
subject: Why does it give exception
It's not a secret anymore!