• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Bear Bibeault
  • Junilu Lacar
Sheriffs:
  • Jeanne Boyarsky
  • Tim Cooke
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • salvin francis
  • Frits Walraven
Bartenders:
  • Scott Selikoff
  • Piet Souris
  • Carey Brown

why the output is classcastexception ?

 
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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){}
}
 
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Person is not comparable: if you change to this, all works

 
Ranch Hand
Posts: 71
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 .
 
Ranch Hand
Posts: 43
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Won't you be my neighbor? - Fred Rogers. tiny ad:
the value of filler advertising in 2020
https://coderanch.com/t/730886/filler-advertising
    Bookmark Topic Watch Topic
  • New Topic