4

I have taken two arrays in my below code snippet,

String[] things = {"a", "b", "c", "d", "e", "f"};
int[] a1 ={1,2,3,4,5};
System.out.println(Arrays.asList(things).contains("c"));
System.out.println(Arrays.asList(a1).contains(3));

and my outputs are

true false

I know when we use Arrays.asList we get an wrapper object which points to the existing array for random access, but in true sense an object of list interface is not created.

My question here is when the contains method works for string, why does it not work for int.

Saurabh Jhunjhunwala
  • 2,832
  • 3
  • 29
  • 57

2 Answers2

7

Arrays.asList for an int array (or similarly for any primitive array) produces a List<int[]> whose single element is that int array. That's why contains(3) returned false (System.out.println(Arrays.asList(a1).contains(a1)); would return true).

If you call Arrays.asList for an Integer array, you'll get a List<Integer> an contains will work as expected.

Eran
  • 387,369
  • 54
  • 702
  • 768
0

Instead of

int[] a1 ={1,2,3,4,5};
System.out.println(Arrays.asList(a1).contains(3));

you could use:

System.out.println(Arrays.asList(1, 2, 3, 4, 5).contains(3));

The signature of asList() is asList(T... a) ㄧ i.e. it takes a vararg, so there is no need for explicit array creation. The constructor will take care of autoboxing.

ccpizza
  • 28,968
  • 18
  • 162
  • 169