How to add elements in a LinkedList in Java

In this article we will discuss how to add elements in LinkedList and then display them.

Lets create a LinkedList of String i.e.

List<String> listOfStr = new LinkedList<>();

To add elements in LinkedList we will use its add() function i.e.

boolean add(E e)

add() member function of LinkedList always appends the element in the end of LinkedList.

Let’s see how to use the member function to add String elements to LinkedList i.e.

package com.thispointer.java.collections.linkedlist;

import java.util.LinkedList;
import java.util.List;

public class Example1 {

	public static void main(String[] args) {

		// Create a LinkedList of String objects
		List<String> listOfStr = new LinkedList<>();
		
		// Add Elements to LinkedList
		listOfStr.add("ABC");
		listOfStr.add("123");
		listOfStr.add("DEF");

		//Display the List
		System.out.println(listOfStr);

	}
}

Output:

[ABC, 123, DEF]

As we can see the elements in the LinkedList are stored in the order in which they were added. This proves that LinkedList is an ordered collection.

[showads ad=inside_post]

 

In above example we inserted 3 elements at the end of LinkedList.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top