Java ArrayDeque Class: addFirst() Method
public void addFirst(E e)
The addFirst() method is used to insert an given element at the front of this deque.
Package: java.util
Java Platform: Java SE 8
Syntax:
addFirst(E e)
Parameters:
Name | Description |
---|---|
e | The element to add. |
Return Value Type: void
Throws:
NullPointerException - if the specified element is null
Pictorial Presentation
Example: Java ArrayDeque Class: addFirst() Method
import java.util.ArrayDeque;
import java.util.Deque;
public class Main {
public static void main(String[] args) {
// Create an empty array deque with an initial capacity 3
Deque<Integer> deque = new ArrayDeque<Integer>(3);
// Use add() method to add elements in the deque
deque.add(40);
deque.add(50);
deque.add(60);
// Use addFirst() method to add 3 elements
// at the front of the deque and print all the elements
deque.addFirst(30);
for (Integer number : deque) {
System.out.println("Number = " + number);
}
deque.addFirst(20);
System.out.println();
for (Integer number : deque) {
System.out.println("Number = " + number);
}
deque.addFirst(10);
System.out.println();
for (Integer number : deque) {
System.out.println("Number = " + number);
}
}
}
Output:
Number = 30 Number = 40 Number = 50 Number = 60 Number = 20 Number = 30 Number = 40 Number = 50 Number = 60 Number = 10 Number = 20 Number = 30 Number = 40 Number = 50 Number = 60
Java Code Editor:
Previous:add Method
Next:addLast Method
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/java-tutorial/util/arraydeque/java_arraydeque_addfirst.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics