首页 | 新闻 | 新品 | 文库 | 方案 | 视频 | 下载 | 商城 | 开发板 | 数据中心 | 座谈新版 | 培训 | 工具 | 博客 | 论坛 | 百科 | GEC | 活动 | 主题月 | 电子展
返回列表 回复 发帖

Java 容器源码分析之 ArrayList(6)

Java 容器源码分析之 ArrayList(6)

上面从ArrayList中移除元素的所有方法中都没有对移除元素后的数组大小进行调整,这种情况下可能会在移除大量元素后造成空间的浪费。这时候可以通过trimToSize方法将数组大小调整为实际的大小。
1
2
3
4
5
6
7
8
9
10
11
12
13
/**
* Trims the capacity of this ArrayList instance to be the
* list's current size.  An application can use this operation to minimize
* the storage of an ArrayList instance.
*/
public void trimToSize() {
    modCount++;
    if (size < elementData.length) {
        elementData = (size == 0)
          ? EMPTY_ELEMENTDATA
          : Arrays.copyOf(elementData, size);
    }
}
更新及查找
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65

public boolean contains(Object o) {
    return indexOf(o) >= 0;
}

/**
* 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&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;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==null)
                return i;
    } else {
        for (int i = 0; i < size; i++)
            if (o.equals(elementData))
                return i;
    }
    return -1;
}

/**
* Returns the index of the last occurrence of the specified element
* in this list, or -1 if this list does not contain the element.
* More formally, returns the highest index <tt>i</tt> such that
* <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>,
* or -1 if there is no such index.
*/
public int lastIndexOf(Object o) {
    if (o == null) {
        for (int i = size-1; i >= 0; i--)
            if (elementData==null)
                return i;
    } else {
        for (int i = size-1; i >= 0; i--)
            if (o.equals(elementData))
                return i;
    }
    return -1;
}

/**
* Returns the element at the specified position in this list.
*/
public E get(int index) {
    rangeCheck(index);

    return elementData(index);
}

/**
* Replaces the element at the specified position in this list with
* the specified element.
*/
public E set(int index, E element) {
    rangeCheck(index);

    E oldValue = elementData(index);
    elementData[index] = element;
    return oldValue;
}
基于数组的实现使得更新元素及查找元素变得比较简单。在set方法中不会修改modCount的值。
返回列表