Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Help with sorting ArrayList using Comparator

 
Shanna Ripley
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All

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.



Thanks in advance for any help or suggestions
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Shanna Ripley
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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??

Thanks again
 
Paul Clapham
Sheriff
Posts: 21416
33
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A different method? Good heavens, no. You just need a very small change to the code you wrote.
 
Sunil Kumar
Ranch Hand
Posts: 76
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Shanna Ripley
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks everyone. Of course it had to be that simple
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic