Java Collections Framework:LinkedList-2(Add/Remove)
Adding an element to LinkedList using add(E e) method – Java
Description
Program to add a new element to LinkedList using add(E e) method of LinkedList class.
Example
import java.util.LinkedList; class LinkedListAdd { public static void main(String[] args) { // create a LinkedList LinkedList<String> list = new LinkedList<String>(); // Adding elements to the LinkedList list.add("Harry"); list.add("Ajeet"); list.add("Tom"); list.add("Steve"); // Displaying LinkedList elements System.out.println("LinkedList elements: "+list); // Adding another element list.add("Kate"); // Displaying LinkedList elements after add(E e) System.out.println("LinkedList elements: "+list); } }
Output:
LinkedList elements: [Harry, Ajeet, Tom, Steve] LinkedList elements: [Harry, Ajeet, Tom, Steve, Kate]
LinkedList.add(E e) method
public boolean add(E e)
: Appends the specified element to the end of this list.
This method is equivalent to addLast(E). More at: Java LinkedList.add(E e)
Java – Add element at specific index in LinkedList example
In this tutorial we will learn how to add a new element at specific index in LinkedList. We will be using add(int index, Element E)
method of LinkedList
class to perform this operation.
More about this method from javadoc:public void add(int index, E element)
: Inserts the specified element at the specified position in this list. Shifts the element currently at that position (if any) and any subsequent elements to the right (adds one to their indices).
Example
In this example we have a LinkedList of Strings and we are adding an element to its 5th position(4th index) using add() method. The complete code is as follows:
import java.util.LinkedList; import java.util.Iterator; public class AddElement { public static void main(String[] args) { // Create a LinkedList LinkedList<String> linkedlist = new LinkedList<String>(); // Add elements to LinkedList linkedlist.add("Delhi"); linkedlist.add("Agra"); linkedlist.add("Mysore"); linkedlist.add("Chennai"); linkedlist.add("Pune"); // Adding new Element at 5th Position linkedlist.add(4, "NEW ELEMENT"); // Iterating the list in forward direction System.out.println("LinkedList elements After Addition:"); Iterator it= linkedlist.iterator(); while(it.hasNext()){ System.out.println(it.next()); } } }
Output:
LinkedList elements After Addition: Delhi Agra Mysore Chennai NEW ELEMENT Pune
Java – Remove first and last element from LinkedList example
Example
We have used removeFirst() method to remove first and removeLast() method to remove last element from LinkedList. Method definition and description are as follows:
1)
public E removeFirst()
: Removes and returns the first element from this list.2)
public E removeLast()
: Removes and returns the last element from this list.Complete Code:
Output: