Suppose I have an array in Java
:
int[][] arr = new int[n][2];
and I want to sort it, for example, according to the first value of the second dimension, thus for every element i
, arr[i][0]
.
I saw that in Java
, there exist two similar ways of doing it, and I want to know what the difference is (efficiency, when to use which method,...).
Method 1)
Arrays.sort(arr, (a, b) -> {
a[0] - b[0];
});
Method 2)
Arrays.sort(arr, new Comparator<int[]>(){
@Override
public int compare(int[] a, int[] b) {
return a[0] - b[0];
}
};
Alternative method:
class Test implements Comparable<Test>{
int val0, val1;
// Contructor
public int compareTo(Test t) {
return val0.compareTo(t.val0);
}
}
And then using in the main method:
Arrays.sort(arr);
where arr is:
Test[] arr = new int[n];
Here val0
and val1
are respectively the 0'th and 1st value of the second dimension. I would not create a class to compare one value, but I sometimes use it for more complex systems and this is anyway an other way of creating a comparator, and if I measure the computational time, it is faster, do you know why?
The question is different from this because it is not asking how to compare. It is also different from this, because it takes into account also the Alternative method of class definition. And this one is not specifying about comparing.