why do i get classcast exception for this code

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){}}
[277 byte] By [ivinjacoba] at [2007-11-27 0:50:59]
# 1

because Person doesn't implement Comparable. TreeSet is a SortedSet, it sorts by comparing objects as Comparables. from the docs:

Throws:

ClassCastException - if the specified object cannot be compared with the elements currently in the set.

so in order for the Set to be sorted, you need to give a way of them being sorted, that is, a compareTo method as defined on the Comparable interface

georgemca at 2007-7-11 23:21:34 > top of Java-index,Core,Core APIs...
# 2

basically classcast exception is thrown when the class can not be casted with the proper form that is demanded.

1> in case of set the value should be mutually comparable. but unfortunately in you code you have not implemented comparable interface. you should implement that interface.

2> after using the comparable interface you should implement the method <class object 1>.compateTo(<class object 2>)

the above two process should exclude the exception from you code hopefully.

check out!

subhaja at 2007-7-11 23:21:34 > top of Java-index,Core,Core APIs...