What is the LinkedList.addLast method in Java?

What is the addLast method?

The addLast method of the LinkedList class is used to add the element to the end of the LinkedList.

LinkedList

A LinkedList is a collection of linear data elements. The data part has the value and the reference part has the address link to the next element. The elements are not indexed, so random access such as Array is not possible. Instead, we traverse from the beginning of the list and access the elements.

In Java, the LinkedList is a doubly-linked list implementation of the list and Deque interfaces.

The LinkedList class presents in the java.util package.

Syntax

public void addLast(E e);

Parameter

The addLast method takes the element to be added to the list as a parameter.

Return value

The addLast method doesn’t return any values.

Code

The code below demonstrates how to use the addLast method.

import java.util.LinkedList;
class LinkedListAddLast {
public static void main( String args[] ) {
LinkedList<String> list = new LinkedList<>();
list.addLast("hello");
System.out.println("The list is " + list);
list.addLast("hi");
System.out.println("The list is " + list);
}
}

Explanation

In the code above,

  • In line number 1 we import the LinkedList class.
import java.util.LinkedList;
  • In line number 4 we create a LinkedList object with the name list.
LinkedList<String> list = new LinkedList<>();
  • In line number 5 we use the addLast method of the list object to add an element ("hello") to the end of the list.
  • Then we print the list.
list.addLast("hello");
list; // ["hello"]
  • In line number 7 we use the addLast method of the list object to add another element ("hi") to the end of the list.
  • Then we print the list.
list.addLast("hi");
list; // ["hello", "hi"]

Free Resources