Java 集合 ArrayList lastIndexOf(Object Obj)方法

来源:这里教程网 时间:2026-02-17 20:13:09 作者:

方法lastIndexOf(Object obj)返回ArrayList中指定元素的最后一次出现的索引。如果列表中不存在指定的元素,则返回 -1。

public int lastIndexOf(Object obj)
这将返回ArrayList中元素Obj的最后一次出现的索引。

在下面的示例中,我们有一个Integer ArrayList,它具有很少的重复元素。我们使用lastIndexof 方法获取少数元素的最后一个索引。

package beginnersbook.com;import java.util.ArrayList;public class LastIndexOfExample {  public static void main(String args[]) {      //ArrayList of Integer Type      ArrayList<Integer> al = new ArrayList<Integer>();      al.add(1);      al.add(88);      al.add(9);      al.add(17);      al.add(17);      al.add(9);      al.add(17);      al.add(91);      al.add(27);      al.add(1);      al.add(17);      System.out.println("Last occurrence of element 1: "+al.lastIndexOf(1));      System.out.println("Last occurrence of element 9: "+al.lastIndexOf(9));      System.out.println("Last occurrence of element 17: "+al.lastIndexOf(17));      System.out.println("Last occurrence of element 91: "+al.lastIndexOf(91));      System.out.println("Last occurrence of element 88: "+al.lastIndexOf(88));    }}

输出:

Last occurrence of element 1: 9Last occurrence of element 9: 5Last occurrence of element 17: 10Last occurrence of element 91: 7Last occurrence of element 88: 1

相关推荐