How To Add Element At The Beginning Of LinkedList?
In this article, we will see the addFirst() method of the LinkedList class in Java with example.
Introduction
LinkedList internally uses doubly linkedlist for storing the variables. That’s why LinkedList is preferred when our frequeent operatioon is insertion and deletion.
To insert the elements with an ease at the beginning of the LinkedList, the Language Develoopers have provided the addFirst()
method.
LinkedList addFirst()
Method
The addFirst() method will inserts the specified element at the beginning of this list.
The method signature for addFirst()
method is gioven below.
1
public void addFirst(E e)
Here, e
is an element to be added at the beginning of the List.
The return type of this method is void
, it means, this method do not return anything.
I have given a simple Java program for the addFirst()
method below.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import java.util.LinkedList;
public class LinkedListAddFirst {
public static void main(String[] args) {
LinkedList<String> linkedList = new LinkedList<String>();
linkedList.add("Austin");
linkedList.add("Boston");
linkedList.add("Atlanta");
linkedList.add("Madison");
linkedList.add("Columbia");
System.out.println(linkedList);
// add element at the beginning
linkedList.addFirst("Albany");
System.out.println(linkedList);
}
}
Output:
1
2
[Austin, Boston, Atlanta, Madison, Columbia]
[Albany, Austin, Boston, Atlanta, Madison, Columbia]
Conclusion
1
public void addFirst(E e)
The addFirst()
method will inserts the specified element at the beginning of this list.
The example java programs given in the above tutorial can be found at this GitHub Repository.
Let me know you thoughts or suggestions on the topic discussed above in comment section below.
Join Newsletter
Get the latest tutorials right in your inbox. We never spam!