简体   繁体   中英

Sorting a 2d array in Java

Im having a little of a hard time figuring out the specifics of a line of code that sorts a 2d array of integers.

The array that is being sorted is an array that has arrays inside that only have two numbers, I am trying to figure out if (a, b) refers to two separate 2d arrays and if (a[0], b[0]) refers to the numbers within the 2d arrays?

Arrays.sort(sortedIntervals, (a, b) -> Integer.compare(a[0], b[0]));

You can use key extractor and comparator chaining :

int[][] arr2d = {{1, 3, 6}, {1, 2, 3}, {0, 2, 3}};

// sorting the rows of a 2d array first by
// the first column, then by the second column
Arrays.sort(arr2d, Comparator
        .<int[]>comparingInt(row -> row[0])
        .thenComparingInt(row -> row[1]));

System.out.println(Arrays.deepToString(arr2d));
// [[0, 2, 3], [1, 2, 3], [1, 3, 6]]

Arrays.sort(sortedIntervals, (a,b) -> Integer.compare(a[0], b[0]));

As you can see here there is only one method compare: compare(int,int) . So a[0] must be a int (or a java.lang.Integer, respecievly).

Since there is only one method accepting a lambda as second parameter it must be this method . And it's javadoc sais a and b are direct elements of the array sortedIntervals and a and b must be an array of ints.

So there is no other option than sortedIntervals is a 2dim array of integers. Since we can access a[0] and b[0] we can expect that all direct elements of sortedIntervals have in their first position can be cast to int .

Also we can predict that

int[][] sortedIntervals ={{},{}}; 
int[][] sortedIntervals ={{6},{}}; 
int[][] sortedIntervals ={{},{6}}; 

will always throw a ArrayIndexOutOfBoundsException inside the lambda because the index 0 does not exists in at least one of the elements.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM