List<String> a = new ArrayList<String>();
List<String> b = new ArrayList<String>();
a.add("apple");
a.add("orange");
System.out.println(a.containsAll(b));
The above program prints a True. Dont understand why is it printing True?
The containsAll() method of Java Set is used to check whether two sets contain the same elements or not. It takes one set as a parameter and returns True if all of the elements of this set is present in the other set. Syntax: public boolean containsAll(Collection C) Parameters: The parameter C is a Collection.
The syntax of the containsAll() method is: arraylist. containsAll(Collection c); Here, arraylist is an object of the ArrayList class.
The containsAll() method of List interface in Java is used to check if this List contains all of the elements in the specified Collection. So basically it is used to check if a List contains a set of elements or not.
The ArrayList. containsAll() method returns a boolean , such that: The return value is true if the list contains all the elements present in the collection c . The return value is false if the list does not contain all the elements present in the collection c .
Because B
is empty. A
contains everything in B
.
Because b
is empty. Therefore there is nothing in b
that is not in a
.
It's a matter of logic: does A contain all the elements inside B?
This can be seen as for each element in B, does this element belong to A too?
You can understand that the condition is true, since B is empty, there is no element to check: for each element in B, so for no element.
List.ContainsAll will return true if the list contains all of the elements within the target. Because B is empty A contains all the same elements as B.
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