1

In Java, I'm trying to know whether an Integer is in an ArrayList<Integer>. I tried using this general solution, which warns that it doesn't work with arrays of primitives. That shouldn't be a problem, since Integers aren't primitives (ints are).

ArrayList<Integer> ary = new ArrayList<Integer>();
ary.add(2);

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

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

Community
  • 1
  • 1
JoseHdez_2
  • 4,040
  • 6
  • 27
  • 44
  • 1
    Why do you call `Arrays.asList(ary)`? `ary` was declared as an `ArrayList`? – bradimus Aug 19 '16 at 16:39
  • Sorry, I didn't realize `ArrayList` inherited from `List` and thus already had a `contains()` method... This was kind of a trivial question, so I'll leave it up to the community to decide whether to keep it or not. – JoseHdez_2 Aug 19 '16 at 16:47

3 Answers3

4

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 <T> List<T> 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).

Nicolas Filotto
  • 43,537
  • 11
  • 94
  • 122
1

You don't need asList() as ArrayList itself a list. Also you don't need String.format() to print the result. Just do in this way. This returns true :

System.out.println(ary.contains(2));
Shahid
  • 2,288
  • 1
  • 14
  • 24
1

The problem is that you're trying to coerce your ArrayList to a List when it already is. Arrays.asList takes an array or variable number of arguments and adds all of these to a list. All you need to do is call System.out.println(ary.contains(2));

Jacob
  • 91
  • 1
  • 9