I'm deeply confused by why the first block of code can compile, while the second block of code can't compile.
Can compile
int[][] arr = {{2,2}, {1,2}, {3,4}};
List<int[]> list = Arrays.asList(arr);
// sort by first element
list.sort(Comparator.comparingInt(x -> x[0]));
Cannot compile. Error is "Array type expected; found: 'java.lang.Object'"
int[][] arr = {{2,2}, {1,2}, {3,4}};
List<int[]> list = Arrays.asList(arr);
// sort by first element, then by second element
list.sort(Comparator.comparingInt(x -> x[0]).thenComparingInt( x -> x[1]));
In order to fix the error, I had to do
list.sort(Comparator.comparingInt(x -> ((int[])x)[0]).thenComparingInt( x -> ((int[])x)[1]));
My question is, why I had to typecast if calling comparingInt
and then thenComparingInt
, while typecast is not needed if I was only calling comparingInt
?