Add a single element to a LinkedList in Java


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);

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 30-Jul-2019

251 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements