Java Arraylist.lastIndexOf()方法详解

IT 文章2年前 (2023)发布 小编
0 0 0

了解如何使用 ArrayList.lastIndexOf() 方法获取 ArrayList 中元素最后一次出现的索引。若要获取第一次出现的索引,请使用 indexOf() 方法。

1. ArrayList.lastIndexOf() API

lastIndexOf(e) 返回此列表中指定元素 e 最后一次出现的索引。如果列表不包含元素,它将返回 -1 

public int lastIndexOf(Object object)

lastIndexOf() 只接受一个参数对象,需要在列表中搜索其最后一个索引位置。

ad

程序员导航

优网导航旗下整合全网优质开发资源,一站式IT编程学习与工具大全网站

  • index – 如果找到元素,则元素的最后一个索引位置。
  • -1 – 如果未找到该元素。

2. ArrayList lastIndexOf()示例

以下 Java 程序获取 ArrayList 的最后一个索引。在此示例中,我们寻找字符串 “alex” 和 “hello” 的最后一次出现。

  • 字符串 “alex” 在列表中出现三次,第二次出现在索引位置 6。
  • 字符串 “hello” 不在列表中。

请注意,ArrayList 的索引从 0 开始。

ArrayList<String> list = new ArrayList<>(Arrays.asList("alex", "brian", "charles","alex","dough","gary","alex","harry"));
int lastIndex = list.lastIndexOf("alex");
System.out.println(lastIndex);
lastIndex = list.lastIndexOf("hello");
System.out.println(lastIndex);

程序输出:

6
-1

以上就是Java Arraylist.lastIndexOf()方法详解的全部内容。

ad

AI 工具导航

优网导航旗下AI工具导航,精选全球千款优质 AI 工具集

© 版权声明

相关文章

暂无评论

暂无评论...