Java LinkedList addLast()

In this guide, you will learn about the LinkedList addLast() method in Java programming and how to use it with an example.

1. LinkedList addLast() Method Overview

Definition:

The addLast() method of the LinkedList class in Java is used to append the given element to the end of the list. The LinkedList class is part of Java's collections framework and implements the List and Deque interfaces.

Syntax:

public void addLast(E e)

Parameters:

- e: the element to add.

Key Points:

- The addLast() method appends the specified element to the end of the list.

- This method throws NullPointerException if the specified element is null and this list does not permit null elements.

- This operation is equivalent to add(e).

- The addLast() method is part of the java.util.LinkedList class.

2. LinkedList addLast() Method Example

import java.util.LinkedList;

public class LinkedListAddLastExample {

    public static void main(String[] args) {
        LinkedList<String> linkedList = new LinkedList<>();

        // Adding elements to the LinkedList
        linkedList.add("Element 1");
        linkedList.add("Element 2");
        linkedList.add("Element 3");

        // Printing the original LinkedList
        System.out.println("Original LinkedList: " + linkedList);

        // Using addLast() to add an element at the end of the LinkedList
        linkedList.addLast("Element 4");
        System.out.println("LinkedList after addLast(): " + linkedList);

        // Adding another element using addLast()
        linkedList.addLast("Element 5");
        System.out.println("LinkedList after another addLast(): " + linkedList);
    }
}

Output:

Original LinkedList: [Element 1, Element 2, Element 3]
LinkedList after addLast(): [Element 1, Element 2, Element 3, Element 4]
LinkedList after another addLast(): [Element 1, Element 2, Element 3, Element 4, Element 5]

Explanation:

In this example, a LinkedList is created and populated with some elements. 

The addLast() method is then used to append elements at the end of the LinkedList. 

The output demonstrates the LinkedList at its initial state, after the first call to addLast(), and after the second call to addLast(), verifying that the elements are indeed appended to the end of the list.

Comments