1

考虑以下代码段,

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));
    }

它为我返回了预期Integer[]String[]结果

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]

但它并没有逆转int[]. 我真的不明白为什么。我提到了这个 SO 问题(Collections.reverse 不能正常工作),但它并没有帮助我真正理解为什么原语没有被反转回来并填充原始 int[] 传递。

4

2 回答 2

3

Arrays.asList的 forint[]数组不会产生您认为的结果。没有办法List<int>在Java 中创建一个,因此,您只需创建一个List<int[]>,即单个项目的列表,其中该项目是您的原始int[]数组。如果您反转该单个项目,那么您将获得该项目,这就是为什么当您打印其反转的内容时它看起来好像没有发生任何事情。

混乱似乎来自期望当你打电话时List.asList(int[])你应该得到一个装箱的整数数组,即List<Integer>,但事实并非如此。Java中没有聚合自动装箱之类的东西,正如另一个答案中所解释的那样,编译器假设您想要为该int[]数组创建单个元素的列表。

于 2020-07-26T06:00:37.950 回答
1

Arrays.asList(arr)返回 a List<int[]>,其唯一元素是您的原始数组。当你反转List单个元素的 a 时,结果是一样的List

这种行为的原因是<T> List<T> asList(T... a)接受一些泛型类型参数的数组T,并且T必须是引用类型。它不能是原始的。因此,当您传递 an 时int[]T是 an int[](这是一个引用类型)而不是原始int.

Integer[]and的行为String[]是不同的,因为IntegerandString都是引用类型,所以Arrays.asList()返回一个List<Integer>forInteger[]和一个List<String>for String[]

于 2020-07-26T05:59:49.647 回答