• Post Reply Bookmark Topic Watch Topic
  • New Topic

ClassCastException  RSS feed

 
Shanthi Murugeson
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Could you please explain why this code gives ClassCastException?

import java.util.*;

public class ClassCastDemo
{
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){}
}

Regards,
Shanthi
 
Svend Rost
Ranch Hand
Posts: 904
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Where does it give this exception, and why do you think it gives a
ClassCastException ?

/Svend Rost, who'll check back later
 
Shanthi Murugeson
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
when i run this program it gives an exception like this -
java.lang.ClassCastException
at java.util.TreeMap.compare(TreeMap.java:1085)
at java.util.TreeMap.put(TreeMap.java:463)
at java.util.TreeSet.add(TreeSet.java:209)
at ClassCastDemo.main(ClassCastDemo.java:10)
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
From the Javadoc for TreeSet's constructor:


Constructs a new, empty set, sorted according to the elements' natural order. All elements inserted into the set must implement the Comparable interface. Furthermore, all such elements must be mutually comparable: e1.compareTo(e2) must not throw a ClassCastException for any elements e1 and e2 in the set. If the user attempts to add an element to the set that violates this constraint (for example, the user attempts to add a string element to a set whose elements are integers), the add(Object) call will throw a ClassCastException.


You're violating the constraint I've shown in boldface: your Person class doesn't implement Comparable. If you want to use TreeSet without making Person implement Comparable, then you need to create another class that implements java.util.Comparator, and pass that to the TreeSet constructor.
[ March 01, 2007: Message edited by: Ernest Friedman-Hill ]
 
Shanthi Murugeson
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot for explaining in a detailed way. I got my mistake.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!