Results 1 to 3 of 3
  1. #1
    pHew is offline Member
    Join Date
    Jan 2008
    Posts
    2
    Rep Power
    0

    Default ClassCastException in TreeSet

    Hello Java guys,

    I have a problem. I keep getting a ClassCastException I don't understand. Let me tell you what happens:

    Java Code:
    Set<A> mySet = new HashSet<A>();
    (filling mySet with objects of type A)

    Now I want to order the Set:

    Java Code:
    Set<A> sortedSet = new TreeSet<A>(mySet);
    BANG! ClassCastException in TreeMap.compare

    I don't understand it. All the objects in mySet are of type A. Why could he be wanting to cast them anyway?

    BTW, the toString() method of type A has been rewritten to return the member String name. If that has something to do with it.

    Thanks for reading this,
    pHew

  2. #2
    pHew is offline Member
    Join Date
    Jan 2008
    Posts
    2
    Rep Power
    0

    Default

    Yay, I have it! I need to implement the "Comparable" interface. Thanks a lot guys!

  3. #3
    gibsonrocker800's Avatar
    gibsonrocker800 is offline Senior Member
    Join Date
    Nov 2007
    Location
    New York
    Posts
    143
    Rep Power
    0

    Default

    Yeah, good job! Keep in mind that TreeSets sort out your data, but how else would it know how to sort it unless you have defined compareTo() in the class, right? For example, say i had a BankAccount class, which should be sorted by balance. For all the TreeSet knows, you could want it to be sorted by the account number. That's why you must define compareTo() and make it implement Comparable.

    "This class guarantees that the sorted set will be in ascending element order, sorted according to the natural order of the elements ([see Comparable), or by the comparator provided at set creation time, depending on which constructor is used."

Similar Threads

  1. TreeSet Demonstration
    By Java Tip in forum java.lang
    Replies: 0
    Last Post: 04-15-2008, 08:34 PM
  2. Working with HashSet and TreeSet
    By Java Tip in forum java.lang
    Replies: 0
    Last Post: 04-15-2008, 08:34 PM
  3. ClassCastException
    By Ed in forum New To Java
    Replies: 2
    Last Post: 07-04-2007, 06:26 AM
  4. ClassCastException
    By Felissa in forum New To Java
    Replies: 2
    Last Post: 07-04-2007, 06:06 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •