Detailed Explanation of the Java LinkedList addFirst() Method
addFirst() Is LinkedList is an important method of the class, used to insert the specified element at the beginning of the linked list.
Method Syntax
public void addFirst(E e)
Parameter Description
E e: The element to add at the beginning of the linked list
Return Value
This method has no return value (void).
How the addFirst() Method Works
addFirst() The working principle of the method can be simply described as:
- Create a new node (Node) object
- Set the new node's
nextpointer to point to the current head node - Set the current head node's
prevpointer to point to the new node - Set the linked list's
headpointer to the new node - If the linked list was previously empty, also point the tail node to the new node
- Increment the linked list's size counter (size++)
Time Complexity
The time complexity of the addFirst() method is O(1), because no matter how large the linked list is, it only needs to perform a fixed number of operations.
Usage examples
Let us look at a few examples to see addFirst() the specific usage of the method.
Example 1: Basic usage
Example
import
java.util.LinkedList
;
public
class
AddFirstExample
{
public
static
void
main
(
String
[
]
args
)
{
// Create a LinkedList
LinkedList
<
String
fruits
=
new
LinkedList
<>
(
);
// Add initial elements
fruits.
add
(
"Banana"
)
;
fruits.
add
(
"Orange"
)
;
System
.
out
.
println
(
"Original linked list: "
fruits
)
;
// Output: [Banana, Orange]
// Use addFirst() to add an element at the beginning
fruits.
addFirst
(
"Apple"
)
;
System
.
out
.
println
(
"Linked list after adding: "
fruits
)
;
// Output: [Apple, Banana, Orange]
}
}
Example 2: Consecutive Adds
Example
import
java.util.LinkedList
;
public
class
ContinuousAddFirst
{
public
static
void
main
(
String
[
]
args
)
{
LinkedList
<
Integer
numbers
=
new
LinkedList
<>
(
);
// Consecutively use addFirst() to add elements
numbers.
addFirst
(
3
)
;
numbers.
addFirst
(
2
)
;
numbers.
addFirst
(
1
)
;
System
.
out
.
println
(
numbers
)
;
// Output: [1, 2, 3]
// Note the relationship between the add order and the final result order
}
}
Example 3: Difference from the add() Method
Example
import
java.util.LinkedList
;
public
class
AddVsAddFirst
{
public
static
void
main
(
String
[
]
args
)
{
LinkedList
<
String
list1
=
new
LinkedList
<>
(
);
LinkedList
<
String
list2
=
new
LinkedList
<>
(
);
// Use the add() method to add elements
list1.
add
(
"A"
)
;
list1.
add
(
"B"
)
;
list1.
add
(
"C"
)
;
// Use addFirst() to add the same elements
list2.
addFirst
(
"C"
)
;
list2.
addFirst
(
"B"
)
;
list2.
addFirst
(
"A"
)
;
System
.
out
.
println
(
"Using add(): "
list1
)
;
// Output: [A, B, C]
System
.
out
.
println
(
"Using addFirst(): "
list2
)
;
// Output: [A, B, C]
// Although the final results are the same, the add order is reversed
}
}
Notes
When using addFirst() method, note the following points:
1. Difference from the add() method
add()method adds elements to the end of the linked list by defaultaddFirst()method adds elements to the beginning of the linked list
2. Difference from the offerFirst() method
addFirst()May throw an exception in a capacity-restricted queueofferFirst()Returns in a capacity-restricted queuefalseinstead of throwing an exception
3. Null Value Handling
LinkedListallows addingnullvalue, thereforeaddFirst(null)is legal.
4. Thread Safety
LinkedListis not thread-safe; if used in a multi-threaded environmentaddFirst(), external synchronization is required.
Practical Application Scenarios
addFirst() The method is especially useful in the following scenarios:
1. Implement a Stack Structure
Since a stack is a "last in, first out" (LIFO) structure, you can use addFirst() and removeFirst() to simulate stack operations.
Example
LinkedList
<
String
stack
=
new
LinkedList
<>
(
);
stack.
addFirst
(
"Task1"
)
;
// Push
stack.
addFirst
(
"Task2"
)
;
// Push
String
top
=
stack.
removeFirst
(
)
;
// Pop, returns "Task2"
2. Most Recently Used List
When implementing a most recently used (MRU) list, newly accessed items can be added to the beginning of the list.
3. Reverse Operation
By adding elements one by one with addFirst() to a new list, you can reverse the list.
Example
LinkedList
<
Integer
original
=
new
LinkedList
<>
(
Arrays.
asList
(
1
,
2
,
3
)
)
;
LinkedList
<
Integer
reversed
=
new
LinkedList
<>
(
);
for
(
Integer
num
:
original
)
{
reversed.
addFirst
(
num
)
;
}
System
.
out
.
println
(
reversed
)
;
// Output: [3, 2, 1]
Performance considerations
addFirst() The method inserts a new entry in the user profile table in the LinkedList has very good performance in this regard, because it only needs to:
- Create a new node
- Adjust a few pointers
No matter how large the linked list is, the time for these operations is constant (O(1) time complexity). This contrasts with ArrayList 's add(0, element) operations, which need to move all existing elements (O(n) time complexity).
Therefore, if you need to frequently add elements at the beginning of a collection,LinkedList is better than ArrayList a better choice.
Frequently Asked Questions
Q1: Does addFirst() overwrite existing elements?
No,addFirst()It just inserts a new element at the beginning of the list and does not overwrite any existing elements.
Q2: Does addFirst() still work if the list is empty?
Yes, if the list is empty,addFirst() it will add the new element as the first and only element of the list.
Q3: What is the difference between addFirst() and push()?
inLinkedListin,addFirst()andpush()is an identical method.push()It is justaddFirst()another name for, used to makeLinkedListusable as a stack.
Q4: Why does my IDE show addFirst() as a method of Deque?
BecauseLinkedListimplements theDequeinterface,addFirst()is actuallyDequea method defined in the interface,LinkedListwhich provides its implementation.
Summary
LinkedList 's addFirst() The method is an efficient operation that allows us to insert elements at the beginning of the list. Understanding this method is essential for using LinkedList effectively, especially in scenarios where elements need to be inserted at the beginning of a collection frequently.
Key points review:
addFirst()Insert elements at the beginning of the list- Time complexity is O(1)
- The difference between
add()Methods differ in where they add elements - Commonly used to implement stack structures and most-recently-used lists
- Requires additional synchronization in multi-threaded environments
By using properly addFirst() method, you can fully leverage LinkedList the performance advantages of in specific scenarios.
Java LinkedList