• 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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Devaka Cooray
  • Liutauras Vilda
Sheriffs:
  • Jeanne Boyarsky
  • paul wheaton
  • Henry Wong
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Tim Moores
  • Carey Brown
  • Mikalai Zaikin
Bartenders:
  • Lou Hamers
  • Piet Souris
  • Frits Walraven

TreeSet Ques

 
Ranch Hand
Posts: 60
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi All,

Why does the foll. ques throws ClassCastException

import java.util.*;


class CollectionTest {

public static void main(String args) throws NullPointerException
{

}
public static void main(String args[])
{


try
{
TreeSet s = new TreeSet();
s.add(new Person(10));
s.add(new Person(20));
System.out.println(s);
}
catch(Exception e)
{
System.out.println(e.toString());
}
}

}

class Person
{
Person(int i)
{

}
}

Regards

Nikhil
 
Ranch Hand
Posts: 2412
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The problem is that the TreeSet when created the way you have will only accept objects whose class definitions implement the Comparable interface. You need to implement that interface in Person. It would be a good idea to also override equals() and hashCode() methods in Person also.
 
Ranch Hand
Posts: 584
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Nikhil,

What Keith said is correct !

TreeSet is a kind of Set where its elements are sorted by their natural order.

In order to perform the sort, TreeSet uses the Comparator interface which must be implemented by your Person class.

When using Strings for example, there's no problem because String object implements all needed methods properly.

The code below is the changed version for your Person class. Please check it out :


When checking the output you can see that all elements are sorted by age.

Hope that helps.
 
and POOF! You're gone! But look, this tiny ad is still here:
We need your help - Coderanch server fundraiser
https://coderanch.com/wiki/782867/Coderanch-server-fundraiser
reply
    Bookmark Topic Watch Topic
  • New Topic