1

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.

Giacomo
  • 551
  • 2
  • 4
  • 16
  • 2
    If you google "anonymous class vs lambda" you'll probably get a good answer. – Carcigenicate Oct 18 '19 at 18:50
  • 1
    Thanks to @Carcigenicate's suggestion, here is a helpful link : [SO Question](https://stackoverflow.com/a/24294935/2928853) -> [PDF containing the answer](https://www.oracle.com/technetwork/java/jvmls2013kuksen-2014088.pdf) – jrook Oct 18 '19 at 18:53
  • This “using minus for a comparator” antipattern is really tenacious. Don’t use minus. Minus can overflow. There’s `Integer.compare(int,int)` for your convenience when implementing a comparator manually, but you rarely need it, just use `Arrays.sort(arr, Comparator.comparingInt(a -> a[0]));`. But what’s your question? – Holger Oct 25 '19 at 12:54

0 Answers0