2
int[] sorted = {10,67,68,28};
int[] sortedOriginal = sorted.clone();
Arrays.sort(sorted);

System.out.println(Arrays.asList(sorted).indexOf(sortedOriginal[0]));

In this very simple code I create an array of ints, clone it, and sort the original. After that I try to find the index given a certain value and it returns -1.

This doesn't make sense. Does anyone know why this happens and what the fix is?

mmghu
  • 595
  • 4
  • 15

1 Answers1

5

Arrays.asList(sorted) returns a List having a single int[] element. That's the way it works on primitive arrays, so it doesn't contain sortedOriginal[0] (on the other hand Arrays.asList(sorted).indexOf(sorted) would return 0).

If you use Integer[] arrays, your code will work.

Eran
  • 387,369
  • 54
  • 702
  • 768