0

I want to sort an int array base on element's String value's reverser order.

I can do it like:

int[] nums = new int[]{9, 12, 67};
var list = Arrays.stream(nums).mapToObj(String::valueOf).sorted(Comparator.reverseOrder()).toList();

Thinking of simple Arrays.sort(nums)'s performance far better than streaming api for large int[], I tried:

Arrays.sort(nums, (i, j) -> String.valueOf(j).compareTo(String.valueOf(i)));

it's an error:

reason: no instance(s) of type variable(s) T exist so that int[] conforms to T[]

Can I resolve this error ?

enter image description here

djy
  • 737
  • 6
  • 14
  • No. In a generic method the type argument (what `T` translates to) must be a reference type, it cannot be a primitive such as `int`. There have been talks about introducing type parameters that can also be primitive, but I don’t know whether anything will come out of it or when. – Ole V.V. Feb 28 '23 at 09:38
  • Related and maybe helpful: [How to sort an array of ints using a custom comparator?](https://stackoverflow.com/questions/3699141/how-to-sort-an-array-of-ints-using-a-custom-comparator) – Ole V.V. Feb 28 '23 at 10:25
  • A possible workaround would be if you can declare your array `Integer[]` rather than `int[]`. – Ole V.V. Feb 28 '23 at 10:26
  • One reason why this is impossible or at least unsuitable: the `Comparator` interface is generic and takes a type argument representing the type of items to be compared, and in Java that needs to a reference type. There is no such thing as a comparator comparing `int` values. You would at the least need to use a `Comparator` and box each `int` for each comparison. – Ole V.V. Mar 01 '23 at 06:00

2 Answers2

0

Arrays.sort expects an array of objects, not an array of primitive types like int[]. Maybe use an Integer[] array instead of an int[] array to sort based on the string value.

Integer[] nums = new Integer[]{9, 12, 67};
Arrays.sort(nums, (i, j) -> String.valueOf(j).compareTo(String.valueOf(i)));
System.out.println(Arrays.toString(nums)); // prints [67, 12, 9]

you can also use a List<Integer> and Collections.sort to sort the list:

List<Integer> nums = Arrays.asList(9, 12, 67);
Collections.sort(nums, Comparator.comparingInt(i -> Integer.parseInt(String.valueOf(i)), Comparator.reverseOrder()));
System.out.println(nums); // prints [67, 12, 9]
Lemonina
  • 712
  • 2
  • 14
0

cannot use primitive types!like int、float、long....!

in Arrays.sort(T[] a, Comparator<? super T> c), T[] <=> int[],int[] is not primitive type, but if you use int[] , in Comparator<? super T>, that T will be inferred to be of type int.

You can try to declare a variable of type Comparator<? super int> to see the effect.

Comparator<? super int> aaa;

This is not allowed.

  • @user16320675 My English is not very good, I don't know if I can express clearly.what I mean is, if int[] is allowed, then it must be accepted that T will be deduced to be of type int, which is not allowed. – 时间只会一直走 Feb 28 '23 at 08:23