gptt916 gptt916 - 6 months ago 46
Java Question

sort list of int[] in java

I would like to sort a list of int arrays in java, specifically like so:

1, 2
1, 3
2, 3
1, 4
2, 4
3, 1


Should be sorted into:

1, 2
1, 3
1, 4
2, 3
2, 4
3, 1


I read some other posts, and have been trying to use something like this that was answered for sorting
String[]
:

Collections.sort(listOfStringArrays,new Comparator<String[]>() {
public int compare(String[] strings, String[] otherStrings) {
return strings[1].compareTo(otherStrings[1]);
}
});


by changing it into:

Collections.sort(listOfIntArrays,new Comparator<int[]>() {
public int compare(int[] ints, int[] otherInts) {
return ints[0].compareTo(otherInts[0]);
}
});


But this didn't work, the error was for the return line
Cannot invoke compareTo(int) on the primitive type int


Can someone help me.

Answer

It is normal that you get this error since the .compareTo(Integer) method can only be called from an Integer object. But in your case, you have primitive int elements.

To make your comparison work, you can call the Integer.compare(int, int) method instead like this:

Instead of

return ints[0].compareTo(otherInts[0]);

Use

return Integer.compare(ints[0], otherInts[0]);

You can take a look at Integer#compare method description

Sorting depending on both values

If you want to sort both on first and second value, you can simply transform the two values into one by creating a two digit number (assuming that each value is a digit in the range 0-9).

I suggest you to do like this

return Integer.compare(ints[0] * 10 + ints[1], otherInts[0] * 10 + otherInts[1]);
Comments