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;
}