1. ArrayList 与 LinkedList类中都有:public int indexOf(Object o)方法。两个类的索引值均是从0到集合大小size - 1。
2. 分析 indexOf的源码会发现,如果想要查找的对象引用为null,也可以得到该对象引用的索引,并不会抛出异常。说明两个类都可以存放null引用。
3. 如果集合中存在对象引用o,则返回该对象的索引值;否则,返回-1,表示集合中不存在该对象引用o。
以下是indexOf的源码:
public int indexOf(Object o) {
int index = 0;
if (o==null) {
for (Entry e = header.next; e != header; e = e.next) {
if (e.element==null)
return index;
index++;
}
} else {
for (Entry e = header.next; e != header; e = e.next) {
if (o.equals(e.element))
return index;
index++;
}
}
return -1;
}