JoseHdez_2 JoseHdez_2 - 1 year ago 54
Java Question

Is value in ArrayList<Integer>? (Java)

In Java, I'm trying to know whether an

is in an
I tried using this general solution, which warns that it doesn't work with arrays of primitives. That shouldn't be a problem, since
s aren't primitives (
s are).

ArrayList<Integer> ary = new ArrayList<Integer>();

System.out.println(String.format("%s", Arrays.asList(ary).contains(2)));

Any reason why?
Any help is appreciated, although the less verbose the better.

Answer Source

Any reason why it returns false?

Simply because Arrays.asList(ary) will return a List<ArrayList<Integer>> and you try to find if it contains an Integer which cannot work.

As remainder here is the Javadoc of Arrays.asList(ary)

public static List asList(T... a) Returns a fixed-size list backed by the specified array.

Here as you provide as argument an ArrayList<Integer>, it will return a List of what you provided so a List<ArrayList<Integer>>.

You need to call List#contains(Object) on your list something like ary.contains(myInteger).