addLast
method?The addLast
method of the LinkedList
class is used to add the element to the end of the 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.
public void addLast(E e);
The addLast
method takes the element to be added to the list
as a parameter.
The addLast
method doesn’t return any values.
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);}}
In the code above,
LinkedList
class.import java.util.LinkedList;
LinkedList
object with the name list
.LinkedList<String> list = new LinkedList<>();
addLast
method of the list
object to add an element ("hello"
) to the end of the list.list.addLast("hello");
list; // ["hello"]
addLast
method of the list
object to add another element ("hi"
) to the end of the list.list.addLast("hi");
list; // ["hello", "hi"]