0

I have a list with this kind of values:

list[0] = "myvalue_8" list[1] = "myvalue_9" list[2] = "myvalue_15" list[3] = "myvalue_12"

When I sort my list like that:

Collections.sort(myList);

The result is:

list[0] = "myvalue_12" list[1] = "myvalue_15" list[2] = "myvalue_8" list[3] = "myvalue_9"

instead of:

list[0] = "myvalue_8" list[1] = "myvalue_9" list[2] = "myvalue_12" list[3] = "myvalue_15"

Thank you very much

Anthony
  • 325
  • 2
  • 5
  • 15

1 Answers1

1

Use a Comparator. There you define what to compare and how, in the compare() method you define what should be returned from two of your instances. Here's an example for a String Comparator.

Comparator<String> myComparator = new Comparator<String>() {
  public int compare(final String user1, final String user2) {
    // This would return the ASCII representation of the first character of each string
    return (int) user2.charAt(0) - (int) user1.charAt(0);
  };
};

Then you just call Collections.sort(myList, myComparator);

nKn
  • 13,691
  • 9
  • 45
  • 62