Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

communitycreator
java

What is the Deque.addFirst() method in Java?

Sumit Sharma

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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);
}
}
Using the Deque.addFirst() method in Java

Explanation

  • In line 1: We import the required package.
  • In line 2: We make a Main class.
  • In line 4: We make a main function.
  • In line 6, we declare a deque that consists of Integer type elements.
  • In lines 8-9: We use the Deque.add() method to insert the elements of the deque.
  • In lines 10-11: We use the Deque.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.

RELATED TAGS

communitycreator
java

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring