Java ArrayList.lastIndexOf()方法详解

培训教学 潘老师 7个月前 (10-09) 152 ℃ (0) 扫码查看

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

1.ArrayList.lastIndexOf() API

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

public int lastIndexOf(Object object)

lastIndexOf() 只接受一个参数对象,需要在列表中搜索它的最后一次出现位置。

lastIndexOf() 返回:

  • index:如果找到元素,则返回元素的最后一次出现的索引位置。
  • -1:如果未找到元素。

2.ArrayList.lastIndexOf() 示例

下面的 Java 程序获取数组列表的最后一个索引。在此示例中,我们正在查找字符串“alex”和“hello”的最后一次出现。

字符串 ‘alex’ 在列表中出现三次,最后次出现在索引位置 6。 字符串 ‘hello’ 不在列表中。

请注意,数组列表的索引从 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); //6
lastIndex = list.lastIndexOf("hello");
System.out.println(lastIndex); //-1

版权声明:本站文章,如无说明,均为本站原创,转载请注明文章来源。如有侵权,请联系博主删除。
本文链接:https://www.panziye.com/teach/9390.html
喜欢 (0)
请潘老师喝杯Coffee吧!】
分享 (0)
用户头像
发表我的评论
取消评论
表情 贴图 签到 代码

Hi,您需要填写昵称和邮箱!

  • 昵称【必填】
  • 邮箱【必填】
  • 网址【可选】