9

I have following Java code,

int a[] = new int[] {20, 30} ;
List lis = Arrays.asList(a) ;
System.out.print(lis.contains(20));

However, output is false. Can anybody help me, why this is not giving True ?

2 Answers 2

13

What you get is not a list of integers but a list of integer arrays, i.e. List<int[]>. You can't create collections (like List) of primitive types.

In your case, the lis.contains(20) will create an Integer object with the value 20 and compare that to the int array, which clearly isn't equal.

Try changing the type of the array to Integer and it should work:

Integer a[] = new Integer[] {20, 30} ;
List lis = Arrays.asList(a) ;
System.out.print(lis.contains(20));
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot. Is there any other way to solve this ? Means convert array in such thus can use contains and delete method ?
You can't solve it any other way without library support (or implementing a wrapper List yourself), but if you use Guava, you can use Ints.asList(int[]) on an int[] directly.
1

The static method asList uses as parameter varargs: .... Only by requiring <Integer> you prevent a List<Object> where a is an Object.

int[] a = new int[] {20, 30} ;
List<Integer> lis = Arrays.asList(a) ;
System.out.print(lis.contains(20));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.