What is the Deque.add() method in Java?
In this shot, we will discuss the Deque.add() method, which is present in the Deque interface inside the java.util package.
The Deque.add() method is used to insert the element at the end of the deque if the deque is not full. Otherwise, it throws an IllegalStateException.
Syntax
boolean add(element)
Parameter
The Deque.add() method takes one parameter:
Element: Element to be inserted.
Return
The Deque.add() method returns a boolean value:
True: When the element is inserted successfully in the deque.False: When the element is not inserted successfully in the deque.
Code
Let’s take a look at the below code snippet.
import java.util.*;class Main{public static void main(String[] args){Deque<Integer> d = new LinkedList<Integer>();d.add(212);d.add(23);d.add(621);d.add(1280);System.out.println("Elements in the deque are: "+d);}}
Explanation
- In line 1, we imported the required package.
- In line 2, we made a
Mainclass. - In line 4, we made a
mainfunction. - In line 6, we declared a deque consisting of
Integertype elements. - From lines 8 to 11, we inserted the elements in a deque by using the
Deque.add()method. - In line 13, we displayed the deque elements.
In this way, we can use the Deque.add() method in Java.