3

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?

Max Wallace
  • 3,609
  • 31
  • 42

3 Answers3

9

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>.

Andy Thomas
  • 84,978
  • 11
  • 107
  • 151
  • 1
    I also wanted to note that one still gets false in the second case even after replacing the smaller array {1,2,3} with {1,2,3,4,5}, and true only when the arrays in the two lists are the same via reference comparison (i.e. "=="). – Max Wallace May 04 '13 at 23:09
0

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.

Juned Ahsan
  • 67,789
  • 12
  • 98
  • 136
-1

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.

Community
  • 1
  • 1
Kuchi
  • 4,204
  • 3
  • 29
  • 37