Java 8Object Oriented ProgrammingProgramming

Elements can be added at the beginning of a LinkedList by using the method java.util.LinkedList.addFirst(). This method has a single argument i.e. the element that is to be added at the beginning of the LinkedList.

Elements can be added at the end of a LinkedList by using the method java.util.LinkedList.addLast(). This method has a single argument i.e. the element that is to be added at the end of the LinkedList.

A program that demonstrates this is given as follows −

Example

Live Demo

import java.util.LinkedList;
public class Demo {
public static void main(String[] args) {
System.out.println("The LinkedList is: " + l);
System.out.println("The LinkedList is: " + l);
}
}

Output

The LinkedList is: [Apple, Mango, Pear]
The LinkedList is: [Orange, Apple, Mango, Pear, Guava]

Now let us understand the above program.

LinkedList<String> l = new LinkedList<String>();
System.out.println("The LinkedList is: " + l);
l.addFirst("Orange");
System.out.println("The LinkedList is: " + l);