add
method?The add
method of the LinkedList
class adds an element to the end of the LinkedList
.
A LinkedList
is a collection of linear data elements. Each element, or node, contains data and reference parts.
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.
public boolean add(E e);
The add
method takes the element to be added to the list as a parameter.
The add
method returns true if the element is added to the list.
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);}}
In the code above,
LinkedList
class.import java.util.LinkedList;
LinkedList
object with the name list
.LinkedList<String> list = new LinkedList<>();
add
method of the list
object to add an element ("hello"
) to the list.list.add("hello");
list; // ["hello"]
add
method of the list
object to add another element ("hi"
) to the list.list.add("hi");
list; // ["hello", "hi"]