A linked list is a collection of linear data elements. Each element (node) contains data and reference parts. 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 as in an array is not possible. Instead, we traverse from the beginning of the list and access the elements.
In Java, the
LinkedList
is theimplementation of the List and Deque interfaces. The doubly-linked list A kind of linked list. Each node contains three fields: two link fields(one for the previous element and another for the next element) and one data field. LinkedList
class is present in thejava.util
package.
getLast
methodThe getLast
method can be used to get the last element of the LinkedList
.
public E getLast();
This method does not take any input arguments.
This method returns the last element of the list. If the list is empty then th NoSuchElementException
exception is thrown.
The code below demonstrates how to use the getLast
method:
import java.util.LinkedList;class LinkedListGetLast {public static void main( String args[] ) {LinkedList<String> list = new LinkedList<>();list.add("1");list.add("2");list.add("3");System.out.println("The list is " + list);System.out.println("The last element of the list is " + list.getLast());}}
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 three elements ("1"
, "2"
, "3"
) to the list.list.add("1");
list.add("2");
list.add("3");
getLast
method of the list
object to get the last element of the list.list.getLast(); // "3"