File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes why the output is  classcastexception ? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "why the output is  classcastexception ?" Watch "why the output is  classcastexception ?" New topic
Author

why the output is classcastexception ?

kavitha satteli
Greenhorn

Joined: Jul 31, 2007
Posts: 9
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){}
}
P Ventura
Ranch Hand

Joined: Jan 24, 2007
Posts: 42
Person is not comparable: if you change to this, all works



Objective: SCJP 1.5<br /><a href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Thread.html" target="_blank" rel="nofollow">API</a><br /> <blockquote><font size="1" face="Verdana, Arial">code:</font><hr><pre><font size="2"><br />Double n1 = Double.NaN; Double n2 = Double.NaN;<br /> n1.equals(n2) // true even though Double.NaN != Double.NaN<br />-0.0 == +0.0; // true<br />Double n1 = -0.0;Double n2 = +0.0;<br />n1.equals(n2) // false even though -0.0 == +0.0<br /></font></pre><hr></blockquote>
Madhukar Ojha
Ranch Hand

Joined: Mar 21, 2007
Posts: 71
TreeSet is a container which put objects in sorted order.
In order to sort data , object being added should be of type Comparable .
In class Person implements Comparable interface and implements its method.
When you add any new object , this method will be called for comparison .


SCJP 5 ๑۩۞۩๑♥~~ My Life is My Creation ~~♥๑۩۞۩๑
Andry Dub
Ranch Hand

Joined: Nov 06, 2007
Posts: 43
This code will compile and run without exceptions:

import java.util.*;
public class Test1{
public static void main(String a[]){
Set s = new HashSet(); <--- guess why
s.add(new Person(20));
s.add(new Person(10));
System.out.println(s);
}
}
class Person{
Person(int i){}
}
[ November 13, 2007: Message edited by: Andry Dub ]

Java is my love
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: why the output is classcastexception ?