tsh*_*ang 18 java arrays collections
我希望这段代码能够显示true
:
int[] array = {1, 2};
System.out.println(Arrays.asList(array).contains(1));
Run Code Online (Sandbox Code Playgroud)
Sea*_*oyd 36
该方法Arrays.asList(T ...)
是,当擦除泛型并且变换varargs时,实际上等于类型的方法Arrays.ofList(Object[])
(这是二进制等价,相同方法的JDK 1.4版本).
一个基元数组是Object
(也见这个问题),但不是Object[]
,所以编译器认为你正在使用varargs版本并在你的int数组周围生成一个Object数组.您可以通过添加额外步骤来说明正在发生的事情:
int[] array = {1, 2};
List<int[]> listOfArrays = Arrays.asList(array);
System.out.println(listOfArrays.contains(1));
Run Code Online (Sandbox Code Playgroud)
这编译并等同于您的代码.它显然也会返回错误.
编译器将varargs调用转换为具有单个数组的调用,因此调用需要T ...
带参数的参数的varargs方法T t1, T t2, T t3
等同于调用它,new T[]{t1, t2, t3}
但这里的特殊情况是,如果方法需要,在创建数组之前将使用基元的varargs进行自动装箱一个对象数组.因此编译器认为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));
Run Code Online (Sandbox Code Playgroud)
以下是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});
Run Code Online (Sandbox Code Playgroud)
参考:
但要以一种简单的方式实际解决您的问题:
Apache Commons/Lang(参见Bozho的答案)和Google Guava中有一些库解决方案:
Ints.contains(int[], int)
检查int数组是否包含给定的intInts.asList(int ...)
从int数组创建一个整数ListArrays.asList(ArrayUtils.toObjectArray(array))
Run Code Online (Sandbox Code Playgroud)
(ArrayUtils
来自commons-lang)
但如果你只想打电话contains
就不需要那样.只需使用Arrays.binarySearch(..)
(首先排序数组)
归档时间: |
|
查看次数: |
10756 次 |
最近记录: |