LinkedList add() Method in Java
In Java, the add() method of the LinkedList class is used to add an element to the list. By default, it adds the element to the end of the list, if the index is not specified.
Example: Here, we use the add() method to add a single element to the list.
// Java program to add elements in LinkedList
import java.util.LinkedList;
class Geeks {
public static void main(String[] args) {
// Create a LinkedList
LinkedList<Integer> l = new LinkedList<>();
// Adding elements in
// the list
l.add(100);
System.out.println("" + l);
}
}
Output
[100, 200, 300]
Now there are two versions of LinkedList add() method i.e. one with the specified index and one without any specified index.
1. public boolean add(E e)
Appends the element "e" to the end of the list.
Syntax:
public boolean add( E e)
- Parameter:
E
represents the type of element that theLinkedList
can store. - Return type: This method returns a boolean value.
Example: Here, we use the add() method to add multiple elements to the LinkedList without specifying an index.
// Add elements without specified index
import java.util.LinkedList;
class Geeks {
public static void main(String[] args) {
// Create a LinkedList
LinkedList<Integer> l = new LinkedList<>();
// Adding elements in
// the list
l.add(100);
l.add(200);
l.add(300);
l.add(400);
l.add(500);
System.out.println("The LinkedList is: " + l);
}
}
Output
The LinkedList is: [100, 200, 300, 400, 500]
2. public boolean add(index , element)
Appends the element at the specified index in the LinkedList.
Syntax:
list.add(index , element)
Parameters:
- index: Pass the index where you want to insert the element.
- element: It is the object you want to add to the list.
Example: Here, we use the add() method to add elements to the list with the specified index.
// Add elements with specified index
import java.util.LinkedList;
class Geeks{
public static void main(String[] args) {
// Create a linkedlist
LinkedList<Integer>l = new LinkedList<>();
// Adding elements in
// the list
l.add(100);
l.add(200);
l.add(400);
System.out.println("LinkedList: " + l);
l.add(2, 300);
System.out.println("New LinkedList: " + l);
}
}
Output
LinkedList: [100, 200, 400] New LinkedList: [100, 200, 300, 400]