Java ArrayList lastIndexOf() Method
The lastIndexOf() method returns the last occurrence position of the specified element in the dynamic array.
The syntax of the lastIndexOf() method is:
arraylist.lastIndexOf(Object obj)
**Note:** arraylist is an object of the ArrayList class.
Parameter Description:
- obj - the element to look for
Return Value
Returns the index value of the last occurrence position of the specified element from the dynamic array.
If the obj element appears repeatedly in the dynamic array, returns the index of the last occurrence of obj in the array.
If the specified element does not exist in the dynamic array, the lastIndexOf() method returns -1.
Example
Getting the index value of the last occurrence position of an ArrayList element:
Example
import
java.util.ArrayList
;
class
Main
{
public
static
void
main
(
String
[
]
args
)
{
// Create an array
ArrayList
<
String
sites
=
new
ArrayList
<>
(
);
sites.
add
(
"Google"
)
;
sites.
add
(
"Runoob"
)
;
sites.
add
(
"Taobao"
)
;
sites.
add
(
"Runoob"
)
;
System
.
out
.
println
(
"Website list: "
sites
)
;
// Get the last occurrence position of Runoob
int
position1
=
sites.
lastIndexOf
(
"Runoob"
)
;
System
.
out
.
println
(
"The last occurrence position of Runoob: "
position1
)
;
// Wiki is not in the arraylist
// Returns -1
int
position2
=
sites.
lastIndexOf
(
"Wiki"
)
;
System
.
out
.
println
(
"The last occurrence position of Wiki: "
position2
)
;
}
}
The output of the above program is:
网站列表: [Google, Runoob, Taobao, Runoob]
Runoob 最后出现的位置: 3
Wiki 最后出现的位置: -1
In the example above, we created a dynamic array named sites.
Note these expressions:
// 返回 3
sites.lastIndexOf("Runoob");
// Wiki is not in the dynamic array, returns -1
sites.lastIndexOf("Wiki");
The lastIndexOf() method successfully returned the last occurrence position of Runoob (i.e., 3). The element Wiki does not exist in the arraylist. Therefore, the method returns -1.
If we want to get the index value of the first occurrence position of Runoob, we can use the indexOf() method. To learn more, please visit Java ArrayList indexOf() .
**Note:** We can also use Java ArrayList get() the method to get the element at the specified index position.
Java ArrayList