0

I have a listview populated with contacts. In my Contact class, I have implemented comparable and I have implemented the compareTo method which compares two strings.

With this method, I can call Collections.sort(myList) and it will sort according to name.

My question is, what do I have to do in order to sort based on another category?

Thanks

Ogen
  • 6,499
  • 7
  • 58
  • 124

1 Answers1

1

Well, you could go two ways:

  1. Since you've already started with implemeting the Comparable interface, you could add a flag on the class which states how it should be compared

  2. Another option would be to create classes which implement the Comparator interface (1 class for each sorting method). When sorting, use the 2nd method of Collections.sort() which accepts a Comparator object as well. Then, simply switch between comparator objects when you want to sort differently.

Hope this helps :)

Gil Moshayof
  • 16,633
  • 4
  • 47
  • 58
  • would the answer to this post solve my problem? http://stackoverflow.com/questions/14154127/collections-sortlistt-comparator-super-t-method-example – Ogen Oct 01 '13 at 08:12
  • just another quick question. Why does it say comparators.NAME in his compareTo method? Why not AGE or NAMEANDAGE? – Ogen Oct 01 '13 at 08:51
  • It was just an example on how to use several comparators. – Gil Moshayof Oct 01 '13 at 10:51