Java源码解读——ArrayList

来源:互联网 发布:腾讯与巨人网络 编辑:程序博客网 时间:2024/05/11 15:43

首先我看了下面两篇文章的解读,推荐大家看一下

(一)http://iamxi.iteye.com/blog/1451921

(二)http://iamxi.iteye.com/blog/1451921

ArrayList 的序列化一直是我不明白的地方

private transient E[] elementData; 也就是说  集合中的元素时不会被序列化的,
可是 ArrayList 重写了  private void writeObject(java.io.ObjectOutputStream s)  和 private void readObject(java.io.ObjectInputStream s)  对元素序列化
为什么呢?
因为ArrayList是会开辟多余空间来保存数据的,而系列化和反序列化这些没有存放数据的空间是要消耗更多资源的,所以ArrayList的数组就声明为transient,自己实现write/readObject方法,仅仅系列化已经存放的数据。


ArrayList 在jdk 1.7中比jdk 1.6中多了不少方法 
1、subList(int fromIndex, int toIndex)
Returns a view of the portion of this list between the specified fromIndex, inclusive, and toIndex, exclusive.
很明显这个方法是对ArrayLis的截取,为了实现这个功能ArrayList 增加了一个内部类 SubList(this, 0, fromIndex, toIndex)
这个截取的方法返回的其实是这个内部类,而不是一个新的 ArrayList。只是这个内部类包含的变量、方法和ArrayList基本相同。
2、removeAll(Collection<?> c)   删除集合中包含 c集合中的元素
   Removes from this list all of its elements that are contained in the specified collection.

   retainAll   保留集合中包含 c集合中的元素
   Retains only the elements in this list that are contained in the specified collection.

这两个方法是通过调用 内部方法  batchRemove 实现的
private boolean batchRemove(Collection<?> c, boolean complement) {
        final Object[] elementData = this.elementData;
        int r = 0, w = 0;
        boolean modified = false;
        try {
            for (; r < size; r++)
                if (c.contains(elementData[r]) == complement)///判断逻辑 是否要保留数据
                    elementData[w++] = elementData[r];
        } finally {
            // Preserve behavioral compatibility with AbstractCollection,
            // even if c.contains() throws.
            if (r != size) {
                System.arraycopy(elementData, r,
                                 elementData, w,
                                 size - r);
                w += size - r;
            }
            if (w != size) {
                // clear to let GC do its work
                for (int i = w; i < size; i++)
                    elementData[i] = null;
                modCount += size - w;
                size = w;
                modified = true;
            }
        }
        return modified;
    }

0 0
原创粉丝点击