# java的1.8ArrayList的indexOf函数分析
Returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element. More formally, returns the lowest index i such that (o==null ? get(i)==null : o. equals(get(i))), or -1 if there is no such index.
返回此列表中指定元素第一次出现的索引,如果此列表不包含该元素,则返回 -1。更正式地说,如果满足 (o==null ? get(i)==null : o.equals(get(i))),则返回最小的索引 i;如果不存在这样的索引,则返回 -1。
public int indexOf(Object o) {
// 元素是null
if (o == null) {
// 遍历数组里面是null的元素。
for (int i = 0; i < size; i++)
if (elementData[i]==null)
// 返回是null的元素索引数。
return i;
} else {
// 元素不是null
for (int i = 0; i < size; i++)
// 遍历数组里面元素进行比较,从0索引位置开始。
if (o.equals(elementData[i]))
// 返回第一次出现索引。
return i;
}
// -1 表示:不存在这个元素。
return -1;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# 重要词汇
- 返回 - returns
- 第一次出现 - first occurrence
- 索引 - index
- 指定元素 - the specified element
- 列表 - list
- 包含 - contain
- 更正式地说 - more formally
- 最小的索引 - lowest index
- 满足 - such that
- 不存在 - if there is no