Question

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:

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?

Was it helpful?

Solution

In the second case, each list consists of a single element. The two elements are both int[] arrays. 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>. With an array of Integers, T can be Integer, and the return type List. But with a primitive array, T cannot be an int, because there cannot be a List<int>.

OTHER TIPS

List is a collection of objects and it works great if you put objects in it. 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. 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.

according to this: What is the difference between an int and an Integer in Java and C#?

Integer is an Object and int is a primitive tho they are not directly the same...

So in the Java docs the Collection.containsAll(Object o) wants a Object and not a primitive. Maybe this explains the different

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top