Java.util.ArrayDeque.addFirst() Method

Advertisements


Description

The java.util.ArrayDeque.addFirst(E e) method inserts the specified element E at the front of the deque.

Declaration

Following is the declaration for java.util.ArrayDeque.addFirst() method

public void addFirst(E e)

Parameters

  • e -- The element to be added in the deque.

Return Value

This method does not return any value.

Exception

  • NullPointerException -- if the specified element is null.

Example

The following example shows the usage of java.util.ArrayDeque.addFirst(E) method.

package com.tutorialspoint;

import java.util.ArrayDeque;
import java.util.Deque;

public class ArrayDequeDemo {
   public static void main(String[] args) {
      
      // create an empty array deque with an initial capacity
      Deque<Integer> deque = new ArrayDeque<Integer>(5);

      // use add() method to add elements in the deque
      deque.add(25);
      deque.add(30);
      deque.add(35);

      // use addFirst() method to add element at the front of the deque
      deque.addFirst(10);
      deque.addFirst(15);
      deque.addFirst(20);//now, element 20 will be at the front

      // these elments will be added in continuation with deque.add(35)
      deque.add(45);
      deque.add(40);

      // let us print all the elements available in deque
      for (Integer number : deque) {
         System.out.println("Number = " + number);
      }
   }
}

Let us compile and run the above program, this will produce the following result:

Number = 20
Number = 15
Number = 10
Number = 25
Number = 30
Number = 35
Number = 45
Number = 40



Advertisements
Advertisements