import java.util.ArrayList;
import java.util.Arrays;
public class ListIndexOfExample {
public static void main(String[] args) {
// 创建一个ArrayList并添加一些元素
ArrayList<String> list = new ArrayList<>(Arrays.asList("apple", "banana", "orange", "apple", "grape"));
// 使用indexOf方法查找元素第一次出现的索引
int indexApple = list.indexOf("apple"); // 返回0,因为"apple"第一次出现在索引0处
System.out.println("Index of first 'apple': " + indexApple);
// 使用lastIndexOf方法查找元素最后一次出现的索引
int lastIndexApple = list.lastIndexOf("apple"); // 返回3,因为"apple"最后一次出现在索引3处
System.out.println("Index of last 'apple': " + lastIndexApple);
// 查找不存在的元素
int indexMango = list.indexOf("mango"); // 返回-1,因为"mango"不在列表中
System.out.println("Index of 'mango': " + indexMango);
}
}
indexOf(Object o)
:该方法返回指定元素在列表中第一次出现的索引。如果列表中不包含该元素,则返回 -1
。lastIndexOf(Object o)
:该方法返回指定元素在列表中最后一次出现的索引。如果列表中不包含该元素,则返回 -1
。在示例代码中,我们创建了一个 ArrayList
并添加了一些水果名称。然后使用 indexOf
和 lastIndexOf
方法来查找特定元素的索引位置,并输出结果。
下一篇:java多行注释符
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站