2

At first, I write the following code, but it can't build. Arrays.sort(n, (o1 ,o2) -> o1 % 2 == 0 ? 1 : -1); enter image description here

And then , I write another code to test it. Arrays.sort(n,(o1, o2) -> o1 - o2); but it has a same error message in vs code. And then , I try those code in IDEA , and it has different error messages in the following pictureenter image description here it says Operator '-' cannot be applied to 'T', 'T. And then , I rewrite the code : Arrays.sort(n,(int o1, int o2) -> o1 - o2); enter image description here I don't know why my code doesn't work. And I found the code I write yesterday: Arrays.sort(envelopes,(int []o1,int []o2) -> o1[0] == o2[0] ? o2[1] - o1[1] :o1[0] - o2[0]); and it works well.

arT
  • 23
  • 3

2 Answers2

1

You're experiencing one of the warts of Java's type system that made the otherwise nicely backwards compatible lambdas awkward — int is a primitive type.

There are no generics over primitive types (yet), so there is no Comparator<int>. The signature of the sort method you're trying to use is

public static <T> void sort(T[] a, Comparator<? super T> c)

and T cannot be int (or short, byte, etc.).

One way around this is to box your ints, e.g. with a stream:

Arrays.stream(n).boxed().sorted((i1, i2) -> i1 % 2 == 0 ? 1 : -1)
OhleC
  • 2,821
  • 16
  • 29
0

The method signature sort has the generic type T:

public static <T> void sort(T[] a, Comparator<? super T> c);

Therefore in order to have the behaviour you want, you have to define n as an array of Integer.

This works correctly:

Integer[] n = new Integer[] {1, 2, 3, 4};
Arrays.sort(n, (o1 ,o2) -> o1 % 2 == 0 ? 1 : -1);

A stackoverflow question about generics and primitive types: Why don't Java Generics support primitive types?

frascu
  • 747
  • 5
  • 9