1

Consider the following snippet,

public static void main(String[] args) {
        int[] arr = new int[] {1,2,3,4,5,6,7};
        Collections.reverse(Arrays.asList(arr));
        System.out.println("The value contained in the array is : " + Arrays.toString(arr));
        
        Integer[] arr1 = new Integer[] {1,2,3,4,5,6,7};
        Collections.reverse(Arrays.asList(arr1));
        System.out.println("The value contained in the array is : " + Arrays.toString(arr1));
        
        String[] strings = new String[] {"tom", "cat", "bob", "boss"};
        Collections.reverse(Arrays.asList(strings));
        System.out.println("The value contianed the the array now is : " + Arrays.toString(strings));
    }

It's returning me the expected result for Integer[] and String[] as

The value contained in the array is : [1, 2, 3, 4, 5, 6, 7]
The value contained in the array is : [7, 6, 5, 4, 3, 2, 1]
The value contianed the the array now is : [boss, bob, cat, tom]

but it does not reverse the int[]. I didn't understand why really. I referred to this SO question (Collections.reverse doesn't work correctly) but it didn't help me really to understand why primitives are not reversed back and populated on original int[] passed.

Tom Taylor
  • 3,344
  • 2
  • 38
  • 63

2 Answers2

3

Your Arrays.asList for the int[] array is not producing the result you think. There is no way to create an List<int> in Java so, you are simply creating a List<int[]>, i.e. a list of a single item, where that item is your original int[] array. If you reverse that single item, well, you get that item back, and that's why it appears to you as if nothing had happened when you print its reversed contents.

The confusion seems to come from the expectation that when you call List.asList(int[]) you should be getting back a boxed array of integers, i.e. List<Integer>, but that is not the case. There is no such thing as aggregated auto boxing in Java and as explained in the other answer, the compiler makes the assumption that what you want is to create a list of a single element for that int[] array.

Edwin Dalorzo
  • 76,803
  • 25
  • 144
  • 205
1

Arrays.asList(arr) returns a List<int[]> whose only element is your original array. When you reverse a List of a single element, the result is the same List.

The reason of this behavior is that <T> List<T> asList(T... a) accepts an array of some generic type parameter T, and T must be a reference type. It cannot be a primitive. Therefore, when you pass an int[], T is an int[] (which is a reference type) and not the primitive int.

The behavior for Integer[] and String[] is different, because both Integer and String are reference types, so Arrays.asList() returns a List<Integer> for Integer[] and a List<String> for String[].

Eran
  • 387,369
  • 54
  • 702
  • 768