The LinkedList.push(E e)
method in Java is used to add an element to the front of the LinkedList
. This guide will cover the method’s usage, explain how it works, and provide examples to demonstrate its functionality.
Table of Contents
- Introduction
push
Method Syntax- Examples
- Adding an Element to the Front
- Handling Null Values
- Conclusion
Introduction
The LinkedList.push(E e)
method is a member of the LinkedList
class in Java. It is part of the Deque
interface and allows you to add an element to the front of the LinkedList
, effectively making it the top element of the stack.
push Method Syntax
The syntax for the push
method is as follows:
public void push(E e)
- e: The element to be added to the front of the
LinkedList
.
Examples
Adding an Element to the Front
The push
method can be used to add an element to the front of a LinkedList
.
Example
import java.util.LinkedList;
public class PushExample {
public static void main(String[] args) {
// Creating a LinkedList of Strings
LinkedList<String> list = new LinkedList<>();
// Adding elements to the LinkedList using push()
list.push("Apple");
list.push("Banana");
list.push("Orange");
// Printing the LinkedList
System.out.println("LinkedList: " + list);
}
}
Output:
LinkedList: [Orange, Banana, Apple]
Handling Null Values
The push
method can handle null
values. Adding a null
value to a LinkedList
will include null
as an element at the front of the list.
Example
import java.util.LinkedList;
public class PushNullExample {
public static void main(String[] args) {
// Creating a LinkedList of Strings
LinkedList<String> list = new LinkedList<>();
// Adding elements to the LinkedList, including null
list.push("Apple");
list.push(null);
list.push("Banana");
// Printing the LinkedList
System.out.println("LinkedList: " + list);
}
}
Output:
LinkedList: [Banana, null, Apple]
Conclusion
The LinkedList.push(E e)
method in Java provides a way to add elements to the front of a LinkedList
, similar to how elements are pushed onto a stack. By understanding how to use this method, you can efficiently manage collections of objects in your Java applications. Whether you are adding elements to the front of the list or handling potential null
values, the push
method provides a flexible solution for these tasks.