java - 如何将 int[] 数组转换为 List?

标签 java arrays collections

我希望这段代码显示 true:

int[] array = {1, 2};
System.out.println(Arrays.asList(array).contains(1));

最佳答案

方法 Arrays.asList(T ...) 也就是说,当泛型被删除并转换可变参数时,实际上等于 Arrays.ofList(Object[]) 类型的方法(这是相同方法的二进制等效 JDK 1.4 版本)。

原语数组是 Object (另见 this question ),但不是 Object[] ,因此编译器认为您正在使用 varargs 版本并在您的 int 数组周围生成一个 Object 数组。您可以通过添加一个额外的步骤来说明正在发生的事情:

int[] array = {1, 2};
List<int[]> listOfArrays = Arrays.asList(array);
System.out.println(listOfArrays.contains(1));

这会编译并等效于您的代码。它也显然返回 false。

编译器将可变参数调用转换为单个数组的调用,因此调用需要参数的可变参数方法 T ...带参数T t1, T t2, T t3相当于用 new T[]{t1, t2, t3} 调用它但这里的特殊情况是,如果方法需要一个对象数组,那么在创建数组之前,带有原语的可变参数将被自动装箱。所以编译器认为 int 数组是作为单个 Object 传入的,并创建一个类型为 Object[] 的单元素数组。 , 它传递给 asList() .

所以这里又是上面的代码,编译器内部实现它的方式:

int[] array = {1, 2};
// no generics because of type erasure
List listOfArrays = Arrays.asList(new Object[]{array});
System.out.println(listOfArrays.contains(1));

以下是调用 Arrays.asList() 的一些好方法和坏方法使用 int 值:

// These versions use autoboxing (which is potentially evil),
// but they are simple and readable

// ints are boxed to Integers, then wrapped in an Object[]
List<Integer> good1 = Arrays.asList(1,2,3);
// here we create an Integer[] array, and fill it with boxed ints
List<Integer> good2 = Arrays.asList(new Integer[]{1,2,3});

// These versions don't use autoboxing,
// but they are very verbose and not at all readable:

// this is awful, don't use Integer constructors
List<Integer> ugly1 = Arrays.asList(
    new Integer(1),new Integer(2),new Integer(3)
);
// this is slightly better (it uses the cached pool of Integers),
// but it's still much too verbose
List<Integer> ugly2 = Arrays.asList(
    Integer.valueOf(1), Integer.valueOf(2), Integer.valueOf(3)
);

// And these versions produce compile errors:
// compile error, type is List<int[]>
List<Integer> bad1 = Arrays.asList(new int[]{1,2,3});
// compile error, type is List<Object>
List<Integer> bad2 = Arrays.asList(new Object[]{1,2,3});

引用:


但是要以简单的方式实际解决您的问题:

在 Apache Commons/Lang(参见 Bozho's answer)和 Google Guava 中有一些库解决方案:

关于java - 如何将 int[] 数组转换为 List?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4324633/

相关文章:

java - 如何在 Java 中将 PDF 转换为 JPEG?

java - Google App Engine Java 文本搜索 API 在字符串搜索中的工作方式与 python 不同

javascript - 使用 Angular 提供程序构建 OData $filter URL

arrays - 如何从命令输出的行创建一个数组

Java列表只添加不删除

java - 如何从 Java 源代码中删除不必要的空格?

java - 如果是芬兰语,Java 是否会错误地显示 ISO 639-2 语言?

c - 在堆中分配 C 中的二维数组(不是指针数组)

java - 如何使可变对象列表不可变

php - 如何 array_values laravel 集合?