Results 1 to 3 of 3
Thread: ClassCastException in TreeSet
- 01-15-2008, 12:50 PM #1
Member
- Join Date
- Jan 2008
- Posts
- 2
- Rep Power
- 0
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:
(filling mySet with objects of type A)Java Code:Set<A> mySet = new HashSet<A>();
Now I want to order the Set:
BANG! ClassCastException in TreeMap.compareJava Code:Set<A> sortedSet = new TreeSet<A>(mySet);
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
- 01-15-2008, 01:11 PM #2
Member
- Join Date
- Jan 2008
- Posts
- 2
- Rep Power
- 0
Yay, I have it! I need to implement the "Comparable" interface. Thanks a lot guys!
- 01-16-2008, 12:20 AM #3
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
-
TreeSet Demonstration
By Java Tip in forum java.langReplies: 0Last Post: 04-15-2008, 07:34 PM -
Working with HashSet and TreeSet
By Java Tip in forum java.langReplies: 0Last Post: 04-15-2008, 07:34 PM -
ClassCastException
By Ed in forum New To JavaReplies: 2Last Post: 07-04-2007, 05:26 AM -
ClassCastException
By Felissa in forum New To JavaReplies: 2Last Post: 07-04-2007, 05:06 AM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks