Java LinkedList addLast(E e) Method Example

In our previous article we have learnt how to use addFirst(E e) method which adds the element to the beginning of the LinkedList. In this tutorial we will learn the usage of addLast(E e)  of java.util.LinkedList class this exactly similar to add(E e) method which adds the specified element at the end of the LinkedList.

Signature

public boolean addLast(E e)

This method appends the specified element to the end of this list.e is the element which will be appended and will return true on successful insertion.

Example

The following example shows the usage of java.util.LinkedList.addLast(e) method.

import java.util.LinkedList;

public class AddLastMethodLinkedListExample {
	public static void main(String args[])
	{
		// create an empty LinkedList
		LinkedList l = new LinkedList();
		
		// use add() method to add elements to the LinkedList
		l.add("Element1");
		l.add("Element2");
		l.add("Element3");
		
		//adding new element at the end of the LinkedList using addLast() 
		l.addLast("Element4");
		
		//Printing the elements of the LinkedList
		System.out.println("Elements of the list");
		for(String temp:l)
		{
			System.out.println(temp);
		}
	}
}

Output

Elements of the list
Element1
Element2
Element3
Element4

Leave a Reply

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