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.
Frequently Asked:
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 Reply
You must be logged in to post a comment.