源码如下:
/**
* 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 <tt>i</tt> such that
* <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>,
* or -1 if there is no such index.
*/
public int indexOf(Object o) {
if (o == null) {
for (int i = 0; i < size; i++)
if (elementData[i]==null)
return i;
} else {
for (int i = 0; i < size; i++)
if (o.equals(elementData[i]))
return i;
}
return -1;
}
可以看出,方法中首先判断了传入的对象是否为空,如果为空的话,会去遍历寻找数组中为空的对象,使用==的方式。
因为空对象不能使用equals方法,而且判断对象相等又不能使用==方法,因此找空对象时需要另外使用==的方式遍历寻找。
结果就是分别判断分别查找。
找到对应的对象以后,返回对象当前的下标。
找不到对象的情况,返回-1.