Add a single element to a LinkedList in Java

Java 8Object Oriented ProgrammingProgramming

A single element can be added to a LinkedList by using the java.util.LinkedList.add() method. This method has one parameter parameters i.e. the element that is to be inserted in 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) {
      LinkedList<String> l = new LinkedList<String>();
      l.add("Magic");
      System.out.println("The LinkedList is: " + l);
   }
}

Output

The LinkedList is: [Magic]

Now let us understand the above program.

The LinkedList l is created. Then LinkedList.add() is used to add a single element to the LinkedList. Then the LinkedList is displayed. A code snippet which demonstrates this is as follows −

LinkedList<String> l = new LinkedList<String>();
l.add("Magic");
System.out.println("The LinkedList is: " + l);
raja
Published on 11-Jan-2019 07:10:22
Advertisements