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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With