I have an ArrayList populated with 'Address' objects. I want to order the contents of the ArrayList using the 'Surname' from the Address objects. I've tried to do this using Comparator but I'm doing something wrong. I get the error message....
"java.lang.ClassCastException: Address cannot be cast to java.lang.Comparable"
Does anyyone have any help or advice about what I'm doing wrong??
My Address Class..
And then I used this line of code in another class where I want to write the contents of the ArrayList to a text file.
Shanna Irl wrote:... Address cannot be cast to java.lang.Comparable"...
Your program expects your Address objects to be Comparable. Note that "Comparable" is different than "Comparator." A Comparable object has the ability to compare itself to other objects. A Comparator object has the ability to compare 2 objects to each other.
When you call Collections.sort, you can either call...
Collections.sort(List list), which expects your List to contain Comparable objects. Or you can call...
Collections.sort(List list, Comparator c), in which you provide a Comparator instance to do the comparisons.
You probably just want to implement Comparable instead of Comparator.
"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer sscce.org
Joined: Mar 12, 2010
Thanks Marc that did the trick
I have one more quick question...I changed the code in compareTo() since I'm using Comparable now...this is what I've got..
It's working but in reverse order...I want the items listed from a to z but this way is organising them z to a. Is there a different method I should be using??
Yup something like... Consider A as smaller to B than B as smaller to A.
Just like your sort order changes when you come to know that the numbers your are looking at in the school are not the marks but the rank.