The lastIndexOf()
method will return the index of the last occurrence of the specified element in the ArrayDeque
object.
fun lastIndexOf(element: E): Int
This method takes the parameter element
, which represents the element to be searched in the deque
.
This method returns the last index at which the specified element is present in the deque
.
If the element is not present in the deque
, then -1 is returned.
The method below demonstrates how to use the lastIndexOf()
method.
fun main() {// create a new deque which can have string elementsvar deque = ArrayDeque<String>()// add three elements to dequeudeque.add("one");deque.add("one");deque.add("two");deque.add("three");println("\nThe deque is " + deque);// get lastIndexOf "one"println("\ndeque.lastIndexOf('one') : " + deque.lastIndexOf("one"));// get lastIndexOf "five"println("\ndeque.lastIndexOf('five') : " + deque.lastIndexOf("five"));}
In the code above,
Line 3: We create an ArrayDeque
with the name deque
.
Lines 6–9: We use the add
method to add four elements to the deque
. Now the deque
is {one,one,two,three}.
Line 14: We use the lastIndexOf
method of the deque
object to get the index of the last occurrence of the element “one”. The element “one” is present at two indices: 0 and 1. We get 1
as a result since that is the last occurrence.
Line 17: We use the lastIndexOf
method of the deque
object to get the index of the last occurrence of the element “five”. The element “five” is not present so -1
is returned.