简体   繁体   English

整数和int数组的包含所有行为的差异(Java)

[英]Difference in containsAll behavior for Integer and int arrays (Java)

Could someone possibly explain why the following: 有人可能解释为什么以下:

Integer[] arr1 = {1,2,3,4,5};
Collection<?> numbers = Arrays.asList(new Integer[]{1,2,3});
System.out.println(Arrays.asList(arr1).containsAll(numbers));

print "true", while if we exchange Integer for int like so: 打印“true”,而如果我们像这样交换Integer:

int[] arr2 = {1,2,3,4,5};
Collection<?> numbers2 = Arrays.asList(new int[]{1,2,3});
System.out.println(Arrays.asList(arr2).containsAll(numbers2));

"false" is printed? 打印“假”?

In the second case, each list consists of a single element. 在第二种情况下,每个列表由单个元素组成。 The two elements are both int[] arrays. 这两个元素都是int []数组。 The list containing the larger array does not contain the member of the list containing the smaller array. 包含较大数组的列表不包含包含较小数组的列表的成员。

The Arrays.asList() method accepts a variable argument list of arguments of type T, and returns a List<T> . Arrays.asList()方法接受类型为T的参数的变量参数列表,并返回List<T> With an array of Integers, T can be Integer, and the return type List. 使用整数数组,T可以是Integer,返回类型为List。 But with a primitive array, T cannot be an int, because there cannot be a List<int> . 但是对于原始数组,T不能是int,因为不能有List<int>

List is a collection of objects and it works great if you put objects in it. List是一个对象集合,如果你在其中放置对象,它会很有用。 As you are trying to create a list using primitive array, JVM is kind enough not to throw an exception but it is not able to create the list as you desired. 当您尝试使用原始数组创建列表时,JVM非常友好,不会抛出异常,但无法根据需要创建列表。 And hence you see a difference in outputs when you you create a list with Integer array, which is valid and when you create a list with int array which is syntactically correct but logically against the principle of Collections. 因此,当您使用Integer数组创建列表时,您会看到输出的差异,这是有效的,并且当您使用int数组创建列表时,该列表在语法上是正确的,但逻辑上违反了集合的原则。

according to this: What is the difference between an int and an Integer in Java and C#? 根据这个: Java和C#中的int和Integer有什么区别?

Integer is an Object and int is a primitive tho they are not directly the same... Integer是一个Object,int是原始的,它们不是直接相同的......

So in the Java docs the Collection.containsAll(Object o) wants a Object and not a primitive. 因此,在Java文档中,Collection.containsAll(Object o)需要一个Object而不是一个原语。 Maybe this explains the different 也许这解释了不同

http://docs.oracle.com/javase/6/docs/api/java/util/Collection.html#contains(java.lang.Object) http://docs.oracle.com/javase/6/docs/api/java/util/Collection.html#contains(java.lang.Object)

Didn't know this myself before thanks a lot for your Question. 在感谢你的问题之前,我自己都不知道。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM