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.

3
  • 2
    If you google "anonymous class vs lambda" you'll probably get a good answer. Commented Oct 18, 2019 at 18:50
  • 1
    Thanks to @Carcigenicate's suggestion, here is a helpful link : SO Question -> PDF containing the answer Commented Oct 18, 2019 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? Commented Oct 25, 2019 at 12:54

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.