Suganthan Suganthan - 12 days ago 5
Java Question

Java - Odd behaviour of List contains

Just I came across a snippet of code,

List<String> a = new ArrayList<String>();
a.add("A");
a.add("B");
a.add("C");

List<String> b = new ArrayList<String>();
b.add("A");
b.add("B");
b.add("C");

System.out.println("a.contains(b)"+a.contains(b));


is returning false what I expected is
true
value.

I stunned, to see this behavior of the
contains
method provided by
java
. Is this expected behavior, and what is use of this
contains
method in
List

Answer

a.contains(b) checks is a single element b is contained in the List a, which is clearly false in your example, since none of the elements of a is a List.

You are looking for a.containsAll(b), which checks if all the elements in the Collection b exist in a.

Read the Javadoc :

/**
 * Returns <tt>true</tt> if this list contains the specified element.
 * More formally, returns <tt>true</tt> if and only if this list contains
 * at least one element <tt>e</tt> such that
 * <tt>(o==null&nbsp;?&nbsp;e==null&nbsp;:&nbsp;o.equals(e))</tt>.
 * ...
 */
boolean contains(Object o);

/**
 * Returns <tt>true</tt> if this list contains all of the elements of the
 * specified collection.
 * ...
 */
boolean containsAll(Collection<?> c);
Comments