黑马程序员技术交流社区

标题: LinkedList集合有索引为什么还查找慢? [打印本页]

作者: zhrnghgwsws    时间: 2014-5-19 15:53
标题: LinkedList集合有索引为什么还查找慢?
本帖最后由 zhrnghgwsws 于 2014-5-19 21:23 编辑

LinkedList集合有索引为什么还查找慢?
作者: saheru    时间: 2014-5-19 16:04
ArrayList索引的实现,如果此列表不包含该元素,则返回 -1。:
1
2
3
4
5
6
7
8
9
10
11
12
public int indexOf(Object o) {
if (o == null) {
    for (int i = 0; i < size; i++)
    if (elementData==null)
        return i;
} else {
    for (int i = 0; i < size; i++)
    if (o.equals(elementData))
        return i;
}
return -1;
}



LinkedList索引的实现:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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;
}



ArrayList:基于数组的遍历查找
LinkedList:基于链表的遍历查找
按照对象在内存中存储的顺序去考虑,数组的访问要比链接表快,因为对象都存储在一起。

作者: DxxD    时间: 2015-3-27 10:39
视频里貌似讲的很清楚,查询用的是链表,从头查到尾,一个个查过去、、、




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2