0

I was trying to reverse elements in a character array using the Collections.reverse() method in java. It wasn't reversing them so i took an integer array as was used in the example i was referring to with no success

Here is my code

int[] intarr = {1,2,3,5,7,8};
System.out.println(Arrays.toString(intarr));
Collections.reverse(Arrays.asList(intarr));
System.out.println(Arrays.toString(intarr));

It returns two lists same as the input! what's going wrong here?

1 Answers1

5

Arrays.asList(intarr) doesn't do what you think it does.

Given that intarr is a primitive array, it is not possible to simply turn this into a list; after all, a List<int> is not (yet) legal java.

Thus, that makes a List<int[]> (as in, a list of int arrays), with exactly 1 element in it: Your int array. Reversing a 1-size list doesn't do anything as you might surmise.

There is no one-liner answer to this short of using third party libraries.

rzwitserloot
  • 85,357
  • 5
  • 51
  • 72
  • You down voted me before I had a chance to down vote you (thankfully). I've never been so wrong on an answer. This is crazy and I would have never guessed. That's not too intuitive. So `T` the generic parameter becomes `int[]`? because we passed in one array and that's the only way to match up the arguments. Why does it produce a list of singleton arrays rather than just a List with the original array with it's only element? – Michael Welch Oct 28 '20 at 00:50
  • Thanks for the detailed explanation, i converted the primitive int into it's wrapper class type and the function is working as expected – user3555555 Oct 28 '20 at 00:51
  • This answer isn't quite correct but of course the gist of it is. The `asList` method returns a `List` with the original array in it. I just tested it out for myself. – Michael Welch Oct 28 '20 at 00:56
  • 1
    @MichaelWelch yes, that’s not intuitive. Making `Arrays.asList` a varargs method was a historical mistake. – Holger Oct 28 '20 at 13:35
  • @Holger yeah now that I examine the method signature it's obvious it needs to work the way it does. – Michael Welch Oct 28 '20 at 13:38