The lastIndexOf
method is used to get the index of the last occurrence of the specified element, in the LinkedList
.
A linked list is a collection of linear data elements. Each element or node contains data and reference parts. The data part has the value and the reference part has the address to the next element.
The elements are not indexed so random access is not possible. Instead, we traverse from the beginning of the list and access the elements.
In Java, the
LinkedList
class is the Doubly-linked list implementation of the List and Deque interfaces.
The
LinkedList
class is present in thejava.util
package.
public int lastIndexOf(Object o);
This method takes the element to be searched in the list as a parameter.
This method returns the last index at which the specified element is present in the list
. If the element is not present in the list, then -1
is returned.
The code below demonstrates how to use the lastIndexOf
method.
import java.util.LinkedList;class LinkedListLastIndexOfExample {public static void main( String args[] ) {LinkedList<String> list = new LinkedList<>();list.add("1");list.add("2");list.add("1");System.out.println("The list is " + list);System.out.println("Last Index of element '1' is : " + list.lastIndexOf("1"));System.out.println("Last Index of element '2' is : " + list.lastIndexOf("2"));System.out.println("Last Index of element '3' is : " + list.lastIndexOf("3"));}}
In the code above:
LinkedList
class.import java.util.LinkedList;
LinkedList
objects 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("1");
lastIndexOf
method of the list
object to get the index of the last occurrence of the element "1"
. The element "1"
is present in two indexes 0
and 2
. We get 2
as result.list.indexOf("1"); // 2
lastIndexOf
method of the list
object to get the index of the last occurrence of the element "2"
. The element "2"
is only present at index 1
, so it is returned.list.indexOf("2"); // 1
lastIndexOf
method of the list
object to get the index of the last occurrence of the element "3"
. The element "3"
is not present in the list, so -1
is returned.list.indexOf("3"); // -1