What is the Deque.addFirst() method in Java?
In this shot, we will discuss how to use the Deque.addFirst() method in Java.
The Deque.addFirst() method is present in the Deque interface inside the java.util package.
Deque.addFirst() is used to insert the element at the front of the deque if the deque is not full.
Syntax
boolean addFirst(element)
Parameters
The Deque.addFirst() method takes one parameter:
element: The element to be inserted.
Return value
The Deque.addFirst() method returns a boolean value:
True: The element is successfully inserted in the deque.False: The element is not successfully inserted in the deque.
Code
Let us take a look at the code snippet below.
import java.util.*;class Main{public static void main(String[] args){Deque<Integer> d = new LinkedList<Integer>();d.add(12);d.add(29);d.addFirst(212);d.addFirst(23);System.out.println("Elements in the deque are: "+d);}}
Explanation
- In line
1: We import the required package. - In line
2: We make aMainclass. - In line
4: We make amainfunction. - In line 6, we declare a deque that consists of
Integertype elements. - In lines
8-9: We use theDeque.add()method to insert the elements of the deque. - In lines
10-11: We use theDeque.addFirst()method to insert the elements at the front of the deque. - In line
13: We display the deque elements.
In this way, we can use the Deque.addFirst() method in Java.