ArrayList中indexOf(Object o)方法具有什么功能呢?
下文笔者讲述Arraylist中indexOf(Object o)方法的功能简介说明,如下所示
ArratList之indexOf(Object o)源码
/**
* 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;
}
从源码中,我们可以看出
1.首先判断了传入的对象是否为null
当为空的话,会去遍历寻找数组中为空的对象,使用==的方式。
由于空对象不能使用equals方法,所以需单独使用 == 号进行处理
2.如果不为null
遍历查找,但是使用equals方法
进行判断
-----------------------------------------------------------------------
当找到元素时,则返回元素所在的小标
否则返回-1
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


