Win a copy of Kotlin for Android App Development this week in the Kotlin forum!
  • 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
  • Liutauras Vilda
  • Devaka Cooray
  • Jeanne Boyarsky
  • Bear Bibeault
Sheriffs:
  • Junilu Lacar
  • Paul Clapham
  • Knute Snortum
Saloon Keepers:
  • Ron McLeod
  • Tim Moores
  • Stephan van Hulst
  • salvin francis
  • Carey Brown
Bartenders:
  • Tim Holloway
  • Frits Walraven
  • Ganesh Patekar

why ClasscastException????  RSS feed

 
Ranch Hand
Posts: 481
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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){}
}
 
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
}
}
 
Ranch Hand
Posts: 1277
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
you wont see such questions in the 1.4 exam
 
All of the world's problems can be solved in a garden - Geoff Lawton. Tiny ad:
RavenDB is an Open Source NoSQL Database that’s fully transactional (ACID) across your database
https://coderanch.com/t/704633/RavenDB-Open-Source-NoSQL-Database
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!