1 lastIndexOf源碼
/**
* Returns the index of the last occurrence of the specified element
* in this list, or -1 if this list does not contain the element.
* More formally, returns the highest index <tt>i</tt> such that
* <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>,
* or -1 if there is no such index.
* 返回指定元素在列表中最後一次出現的索引,如果不包含指定元素,則返回-1
*/
public int lastIndexOf(Object o) {
if (o == null) {
for (int i = size-1; i >= 0; i--)
if (elementData[i]==null)
return i;
} else {
for (int i = size-1; i >= 0; i--)
if (o.equals(elementData[i]))
return i;
}
return -1;
}
它和indexOf源碼幾乎一樣,不同的是,lastIndexOf是從列表的尾部開始查找是否包含指定元素,而indexOf是從頭部開始查找。因此,解析可以參考【ArrayList源碼】indexOf源碼及使用
2 lastIndexOf使用
List<Integer> list = new ArrayList<>();
list.add(5);
list.add(3);
list.add(4);
list.add(3)
System.out.println(list.indexOf(3));
List<String>list1 = new ArrayList<>();
list1.add("wo");
list1.add("ni");
list1.add("wo");
System.out.println(list1.indexOf("wo"));
輸出
3
2
3 總結
lastIndexOf返回指定元素在列表中最後一次出現的索引,如果不包含指定元素,則返回-1