您的位置:首页 > 其它

ArrayList与LinkedList方法分析一:查找某个对象引用在集合中的索引(index)

2012-02-25 21:10 696 查看
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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐