Java Utility Library

Java ArrayDeque - addFirst() Method



The java.util.ArrayDeque.addFirst() method is used to add a new element at the front of the deque.

Syntax

public void addFirst(E element)

Here, E is the type of element maintained by the container.


Parameters

element Specify element which need to be added in the deque.

Return Value

void type.

Exception

Throws NullPointerException, if the specified element is null.

Example:

In the example below, the java.util.ArrayDeque.addFirst() method is used to add new element at the front of the deque.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating a ArrayDeque
    ArrayDeque<Integer> MyDeque = new ArrayDeque<Integer>();

    //populating ArrayDeque using addFirst() method
    MyDeque.addFirst(10);
    MyDeque.addFirst(20);
    MyDeque.addFirst(30);
    MyDeque.addFirst(100);
    MyDeque.addFirst(200);

    //printing ArrayDeque
    System.out.println("MyDeque contains: " + MyDeque);   
  }
}

The output of the above code will be:

MyDeque contains: [200, 100, 30, 20, 10]

❮ Java.util - ArrayDeque