The
Stack
class is astack of objects. Last-In-First-Out (LIFO) The element inserted first is processed last and the element inserted last is processed first.
The containsAll()
method checks if all of the elements of the specific collection object are present in the Stack
object.
public boolean containsAll(Collection<?> c)
The collection to be checked for in the Stack
is passed as an argument.
containsAll()
returns true
if all of the elements of the passed collection are present in the Stack
.
import java.util.Stack;import java.util.ArrayList;class containsAll {public static void main( String args[] ) {Stack<Integer> stack = new Stack<>();stack.add(1);stack.add(2);stack.add(3);ArrayList<Integer> list1 = new ArrayList<>();list1.add(1);list1.add(3);System.out.println("The stack is "+ stack);System.out.println("\nlist1 is "+ list1);System.out.println("If stack contains all elements of list1 : "+ stack.containsAll(list1));ArrayList<Integer> list2 = new ArrayList<>();list2.add(4);System.out.println("\nlist2 is "+ list2);System.out.println("If stack contains all elements of list2 : "+ stack.containsAll(list2));}}
In the code above:
In lines 1 and 2: We import the Stack
and ArrayList
classes.
In line 4: We create an object for the Stack
class with the name stack
.
In lines 6 to 8: We add three elements (1,2,3
) to the created stack
object.
In line 10: We create a new ArrayList
object with the name list1
and add the elements 1,3
to it.
In line 16: We call the containsAll()
method to check if all elements of list1
are present in the stack
. In this case, the method returns true
because all the elements of list1
(1,3
) are present in the stack
.
In line 18: We create a new ArrayList
object with the name list2
and add the element 4
to it.
In line 22: We call the conainsAll()
method again to check if all elements of list2
are present in the stack
. In this case, the method returns false
because element 4
of list2
is not present in the stack
.