📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.
🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (176K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
In this guide, you will learn about the LinkedList addFirst() method in Java programming and how to use it with an example.
1. LinkedList addFirst() Method Overview
Definition:
The addFirst() method of the LinkedList class in Java is used to insert the given element at the beginning of the list. LinkedList is part of Java's collections framework and implements the List and Deque interfaces.
Syntax:
public void addFirst(E e)
Parameters:
- e: the element to add.
Key Points:
- The addFirst() method inserts the specified element at the beginning of the list.
- The method throws NullPointerException if the specified element is null and this list does not permit null elements.
- This operation is equivalent to add(0, e).
- The method belongs to java.util.LinkedList class.
2. LinkedList addFirst() Method Example
import java.util.LinkedList;
public class LinkedListAddFirstExample {
public static void main(String[] args) {
LinkedList<String> linkedList = new LinkedList<>();
// Adding elements to the LinkedList
linkedList.add("Element 1");
linkedList.add("Element 2");
linkedList.add("Element 3");
// Printing the original LinkedList
System.out.println("Original LinkedList: " + linkedList);
// Using addFirst() to add an element at the beginning of the LinkedList
linkedList.addFirst("Element 0");
System.out.println("LinkedList after addFirst(): " + linkedList);
// Adding another element using addFirst()
linkedList.addFirst("Element -1");
System.out.println("LinkedList after another addFirst(): " + linkedList);
}
}
Output:
Original LinkedList: [Element 1, Element 2, Element 3] LinkedList after addFirst(): [Element 0, Element 1, Element 2, Element 3] LinkedList after another addFirst(): [Element -1, Element 0, Element 1, Element 2, Element 3]
Explanation:
In this example, a LinkedList is created and populated with some elements.
The addFirst() method is then used to insert elements at the beginning of the LinkedList. The output shows the original LinkedList, and the LinkedList after each call to addFirst(), demonstrating that the new elements are indeed added at the beginning of the list.
Comments
Post a Comment
Leave Comment