Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Arrays.asList works [duplicate]

Tags:

java

arrays

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.

like image 342
Saurabh Jhunjhunwala Avatar asked Mar 17 '23 13:03

Saurabh Jhunjhunwala


1 Answers

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.

like image 81
Eran Avatar answered Mar 28 '23 01:03

Eran