Arrays.asList(INT [])不工作 [英] Arrays.asList(int[]) not working
问题描述
当我运行下面的code,无输出打印。
INT []数组= {3,2,5,4};如果(Arrays.asList(阵列)。载有(3))
{
的System.out.println(该数组包含3);
}
当你传递原语的数组( INT []
你的情况),以 Arrays.asList
,它会创建一个列表与LT; INT []>
用一个单一的元素 - 数组本身。因此,包含(3)
返回false。 包含(阵列)
将返回true。
如果你使用整数[]
而不是 INT []
,它会工作。
整数[]数组= {3,2,5,4};如果(Arrays.asList(阵列)。载有(3))
{
的System.out.println(该数组包含3);
}
进一步的解释:
的签名 asList
是列表< T> asList(T ...)
。一种原始不能代替一个泛型类型参数。因此,当你通过这种方法的 INT []
,整个 INT []
阵列替换 T
,你会得到一个列表与LT; INT []>
。在另一方面,当你传递一个整数[]
来的方法,整数
替换 ŧ
,你会得到一个列表与LT;整数方式>
When I run the following code, no output is printed.
int[] array = {3, 2, 5, 4};
if (Arrays.asList(array).contains(3))
{
System.out.println("The array contains 3");
}
When you pass an array of primitives (int[]
in your case) to Arrays.asList
, it creates a List<int[]>
with a single element - the array itself. Therefore contains(3)
returns false. contains(array)
would return true.
If you'll use Integer[]
instead of int[]
, it will work.
Integer[] array = {3, 2, 5, 4};
if (Arrays.asList(array).contains(3))
{
System.out.println("The array contains 3");
}
A further explanation :
The signature of asList
is List<T> asList(T...)
. A primitive can't replace a generic type parameter. Therefore, when you pass to this method an int[]
, the entire int[]
array replaces T
and you get a List<int[]>
. On the other hand, when you pass an Integer[]
to that method, Integer
replaces T
and you get a List<Integer>
.
这篇关于Arrays.asList(INT [])不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!