要比较List
使用indexOf方法:
List list = new ArrayList<>();
list.add(1);
list.add(2);
list.add(3);
int index1 = list.indexOf(2);
System.out.println("First occurrence of 2 at index: " + index1);
int index2 = list.indexOf(4);
System.out.println("First occurrence of 4 at index: " + index2);
输出结果:
First occurrence of 2 at index: 1
First occurrence of 4 at index: -1
indexOf方法返回指定元素第一次出现的索引,如果列表不包含该元素,则返回-1。
使用lastIndexOf方法:
List list = new ArrayList<>();
list.add(1);
list.add(2);
list.add(2);
list.add(3);
int index1 = list.lastIndexOf(2);
System.out.println("Last occurrence of 2 at index: " + index1);
int index2 = list.lastIndexOf(4);
System.out.println("Last occurrence of 4 at index: " + index2);
输出结果:
Last occurrence of 2 at index: 2
Last occurrence of 4 at index: -1
lastIndexOf方法返回指定元素最后一次出现的索引,如果列表不包含该元素,则返回-1。
通过使用indexOf方法和lastIndexOf方法,可以比较List
上一篇:比较领域以允许行动