*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes why ClasscastException???? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "why ClasscastException????" Watch "why ClasscastException????" New topic
Author

why ClasscastException????

Karu Raj
Ranch Hand

Joined: Aug 31, 2005
Posts: 479
why ClasscastException??? do explain me clearly

i didnot get it

import java.util.*;
public class test1{
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){}
}
Cheenu Subramanian
Ranch Hand

Joined: Aug 15, 2005
Posts: 40
TreeSet implements SortedSet. When elements are added to the TreeSet collection it has to compare the to-be-added object against the existing collection elements. So either the to-be-added object has to implement comparable or a comparator has to be provided during TreeSet creation. If u try to add only one element u wont get this exception.

Try this and hope this is of some use.

import java.util.*;
public class SetTest{
public static void main(String a[]){
Set s = new TreeSet();
s.add(new Person(20));
s.add(new Person(10));
s.add(new Person(20));
System.out.println(s);
}
}
class Person implements Comparable
{
int i=0;
Person(int i){this.i=i;}
public int compareTo(Object o)
{
if ((o instanceof Person) && (((Person)o).i==i))
return 0;
else
return 1; // not equal
}
}
Niranjan Deshpande
Ranch Hand

Joined: Oct 16, 2005
Posts: 1277
you wont see such questions in the 1.4 exam


SCJP 1.4 - 95% [ My Story ] - SCWCD 1.4 - 91% [ My Story ]
Performance is a compulsion, not a option, if my existence is to be justified.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: why ClasscastException????
 
Similar Threads
ClassCastException
core java
code
TreeSet add method
TreeSet Ques