What is the LinkedList.add method in Java?

What is the add method?

The add method of the LinkedList class adds an element to the end of the LinkedList.

LinkedList

A LinkedList is a collection of linear data elements. Each element, or node, contains data and reference parts.

  • The data part has the value
  • 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 present in the java.util package.

Syntax

public boolean add(E e);

Parameters

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

Return value

The add method returns true if the element is added to the list.

Code

The code below demonstrates how to use the add method.

import java.util.LinkedList;
class LinkedListAdd {
public static void main( String args[] ) {
LinkedList<String> list = new LinkedList<>();
list.add("hello");
System.out.println("The list is " + list);
list.add("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 add method of the list object to add an element ("hello") to the list.
  • Then we print the list.
list.add("hello");
list; // ["hello"]
  • In line number 7 we use the add method of the list object to add another element ("hi") to the list.
  • Then we print the list.
list.add("hi");
list; // ["hello", "hi"]