Class cast exception error

Hi all,

I have an ArrayList which basically is used to add and remove objects to and from it..

Now I would like to have the items sorted and also no repeated items.

I figured a treeset would be the best choice as it sorts the items and keep the user from adding duplicates. However, when I tried to change:

this:

List itemList =new ArrayList();

into this:

Set itemList =new TreeSet();

i get this as soon as I add the 2nd item to the Set (the first item is added fine)

Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: Item cannot be cast to java.lang.Comparable

Thanks guys

PS. The code is HUGE and is impossible to give an example

So maybe you could illuminate me on what that error could be or mean so that I may try to figure out the problem.

[913 byte] By [Xenobiusa] at [2007-11-27 0:14:18]
# 1

> ...

> i get this as soon as I add the 2nd item to the Set

> (the first item is added fine)

>

> Exception in thread "AWT-EventQueue-0"

> java.lang.ClassCastException: Item cannot be cast to

> java.lang.Comparable

If you are going to store objects in your TreeSet, the object in question should implement the Comparable interface: how else should the TreeSet knows how to order you objects?

Details:

http://java.sun.com/docs/books/tutorial/collections/interfaces/order.html

prometheuzza at 2007-7-11 21:59:20 > top of Java-index,Java Essentials,New To Java...
# 2
Cool thanks man :)Il try to implement it and let you know how it went! cheers
Xenobiusa at 2007-7-11 21:59:20 > top of Java-index,Java Essentials,New To Java...
# 3
You're welcome.; )
prometheuzza at 2007-7-11 21:59:20 > top of Java-index,Java Essentials,New To Java...
# 4

So if I have this:

Set<Item> itemList = new TreeSet<Item>();

public void addItem(Item i) {

itemList.add(i);

}

How would the comparator be implemented in this pls?

Thanks

Xenobiusa at 2007-7-11 21:59:20 > top of Java-index,Java Essentials,New To Java...
# 5

> So if I have this:

>

> Set<Item> itemList = new TreeSet<Item>();

>

> public void addItem(Item i) {

> itemList.add(i);

> }

>

> How would the comparator be implemented in this pls?

>

> Thanks

I don't know, because I don't know what attributes reside in your Item class AND on which you want to perform the ordering.

Did you read the link I posted earlier? If so, was there something you didn't understand about it?

Btw, a set called itemList sounds a bit strange. Better call it itemSet or itemCollection.

prometheuzza at 2007-7-11 21:59:20 > top of Java-index,Java Essentials,New To Java...
# 6

Hi again,

Yeah I agree about the itemList instead of itemSet but its already implemented like that in all over the software and would be of minimal problem for now. Once I get the treeset working again I will refactor the List into Set :p

as regards to the item. I only have a String object and would like to sort on that name.

Each class has a String name;

and each name is passed to that. I hope I manage this because I can't figure out. Its a bit difficult to understand but Il read it once more. Do you think you could give me a 2 line code example how it works?

THANKS again :)

Xenobiusa at 2007-7-11 21:59:20 > top of Java-index,Java Essentials,New To Java...
# 7

Lets put this in another way,

I have 3 classes:

class1: DrawGUI

class2: House which contains the treeset of Items and method additem() and removeitem() (see below)

public void addItem(Item i) {

ItemSet.add(i);

}

and same for the removeItem(), addProp() and removeProp()

class3: Item which contains an arrayList of properties and method addProp() and removeProp()

Both Item and House classes have a String name; declared in the class and all methods use this name to communicate/ use the mentioned methods.

I also have the toString method which is over ridden in both classes.

Now I would like to add ITEMS to the class House but unfortunatelly I don't know how to use a comparator so the TreeSet can actually sort the items added.

Could somone kindly help me by giving me a small example combined with my situation?

Thanks a lot! Much appriciated.

Xenobiusa at 2007-7-11 21:59:20 > top of Java-index,Java Essentials,New To Java...
# 8

> Lets put this in another way,

>

> I have 3 classes:

>

> class1: DrawGUI

That is not a very suitable name for a class. It sounds more like a method to me.

> class2: House which contains the treeset of Items and

> method additem() and removeitem() (see below)

>

> public void addItem(Item i) {

> ItemSet.add(i);

> }

>

> and same for the removeItem(), addProp() and

> removeProp()

>

> class3: Item which contains an arrayList of

> properties and method addProp() and removeProp()

Ok.

> Both Item and House classes have a String

> name; declared in the class and all methods use

> this name to communicate/ use the mentioned

> methods.

>

> I also have the toString method which is over ridden

> in both classes.

>

>

> Now I would like to add ITEMS to the class House but

> unfortunatelly I don't know how to use a comparator

> so the TreeSet can actually sort the items added.

>

> Could somone kindly help me by giving me a small

> example combined with my situation?

>

> Thanks a lot! Much appriciated.

class Item implements Comparable<Item> {

// ...

public int compareTo(Item item) {

// your code here

}

// ...

}

When you have properly implemented the compareTo method, your Items added to the TreeSet inside your House class will be ordered the way you defined them.

Again, if you're not sure how to implement the compareTo method, read this:

http://java.sun.com/docs/books/tutorial/collections/interfaces/order.html

prometheuzza at 2007-7-11 21:59:20 > top of Java-index,Java Essentials,New To Java...
# 9

> That is not a very suitable name for a class. It sounds more like a method to me.

Your right. I have renamed it. thanks

> // your code here

I did move one step forward, however, what should I return? and what kind of code should I put? Doesn't the TreeSet sort automatically ? or sould the code be somthing that has to do with the String name;

I thank you once more for your help :)

Xenobiusa at 2007-7-11 21:59:21 > top of Java-index,Java Essentials,New To Java...
# 10

> ...

> I did move one step forward, however, what should I

> return?

An int (as the method signature says):class Item implements Comparable<Item> {

variable X

// ...

public int compareTo(Item that) {

// if this.X is less than that.X return -1

// else if this.X is more than that.X return 1

// else, they must be equal (in some way), so return 0

}

// ...

}

> and what kind of code should I put? Doesn't

> the TreeSet sort automatically ?

No, it sorts automatically based on what you have written inside the compareTo(...) method.

> or sould the code be

> somthing that has to do with the String name;

Could be, like I said before: if you want it to be sorted by their name, you implement it like that.

Did you read the link I posted (twice) carefully? Did you compile and run the examples given there? I would really help you understand how things work if you did so (especially running the examples!).

> I thank you once more for your help :)

You're welcome.

prometheuzza at 2007-7-11 21:59:21 > top of Java-index,Java Essentials,New To Java...
# 11
FANTASTIC !!!! It worked mate!! THANKS now for the last bit... All is left is to use the CASE_INSENSITIVE_SORT and im done :PDoes that go in the declaration of the treeSet or in the compare method?THANKS :P :P :P
Xenobiusa at 2007-7-11 21:59:21 > top of Java-index,Java Essentials,New To Java...
# 12

> FANTASTIC !!!! It worked mate!!

>

> THANKS now for the last bit...

>

> All is left is to use the CASE_INSENSITIVE_SORT and

> im done :P

>

> Does that go in the declaration of the treeSet or in

> the compare method?

>

> THANKS :P :P :P

Aaah, victory, a last!

About the case insensitive part, you could do it like this:

class Item implements Comparable<Item> {

String name;

// ...

public int compareTo(Item that) {

int difference = this.name.toLowerCase().compareTo(that.name.toLowerCase());

if(difference < 0) {

return -1;

} else if(difference > 0) {

return 1;

} else {

return 0;

}

}

// ...

}

Good luck.

prometheuzza at 2007-7-11 21:59:21 > top of Java-index,Java Essentials,New To Java...
# 13

Now that you've managed to find the answer, here is a different way to sort things. It is not done by using/implementing the Comparable interface, but by writing a custom Comparator. This could be useful if you want to sort on different class variables or in different ways (by implementing the Comparable interface you can only sort it in one particular way!).

Here's a demo:class Main {

public static void main(String[] args) {

Item[] items = { new Item("D"), new Item("A"), new Item("c"),

new Item("E"), new Item("f"), new Item("b")};

java.util.Set<Item> caseInSensitiveSet =

new java.util.TreeSet<Item>(new CaseInsensitiveNameComaprator());

caseInSensitiveSet.addAll(java.util.Arrays.asList(items));

java.util.Set<Item> caseSensitiveSet =

new java.util.TreeSet<Item>(new CaseSensitiveNameComaprator());

caseSensitiveSet.addAll(java.util.Arrays.asList(items));

System.out.println("caseInSensitiveSet = "+caseInSensitiveSet);

System.out.println("caseSensitiveSet = "+caseSensitiveSet);

}

}

class Item {

String name;

public Item(String name) { this.name = name; }

public String toString() { return this.name; }

}

class CaseInsensitiveNameComaprator implements java.util.Comparator<Item> {

public int compare(Item o1, Item o2) {

return o1.name.toLowerCase().compareTo(o2.name.toLowerCase());

}

}

class CaseSensitiveNameComaprator implements java.util.Comparator<Item> {

public int compare(Item o1, Item o2) {

return o1.name.compareTo(o2.name);

}

}

Good luck.

prometheuzza at 2007-7-11 21:59:21 > top of Java-index,Java Essentials,New To Java...
# 14

Brilliant!! :P

I found a small snippet in the tutorial you gave me and changed it to my needs. here is how i managed to do it!!

public int compareTo(Item i) {

int lastCmp = name.toLowerCase().compareTo.name.toLowerCase());

return (lastCmp != 0 ? lastCmp : name.compareTo(i.name));

}

Thanks for everything mate il pass some stars now :P :P

Xenobiusa at 2007-7-11 21:59:21 > top of Java-index,Java Essentials,New To Java...