java集合类 ArrayList

ArrayList:

是一个数组队列,与java数组相比更动态,容量不固定(有最大值),可以动态增长;有顺序;可重复;元素可为Null;

不是线程安全的,多线程中可以使用CopyOnWriteArrayList,或者Collections.synchronizedList(list)

public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable

实现List:可以进行增删修改遍历等;

实现RandomAccess:提供随机访问功能,该接口在List中实现。通过元素序号快速获取元素,就是随机访问。

实现Cloneable:覆盖clone(),可被克隆

实现Serializable:可序列化

成员变量:

private static final int DEFAULT_CAPACITY = 10;		//默认初始容量
private static final Object[] EMPTY_ELEMENTDATA = {};	//用于空实例的共享空数组实例
private transient Object[] elementData;			//底层数组,保存了添加到ArrayList的元素;允许null;无法序列化
private int size;				//动态数组实际大小
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;	//扩张最大值   =0x7fffffff-8

 transient修饰符让elementData无法自动序列化,这样的原因是,数组内存储的的元素其实只是一个引用,单单序列化一个引用没有任何意义,反序列化后这些引用都无法在指向原来的对象。ArrayList使用writeObject()实现手工序列化数组内的元素。

具体实现:

构造方法:

    public ArrayList(Collection<? extends E> c) {
        elementData = c.toArray();
        size = elementData.length;
        // c.toArray might (incorrectly) not return Object[] (see 6260652)
        if (elementData.getClass() != Object[].class)
            elementData = Arrays.copyOf(elementData, size, Object[].class);
    }
    public ArrayList() {	//设置默认
        super();
        this.elementData = EMPTY_ELEMENTDATA;
    }
    public ArrayList(int initialCapacity) {
        super();
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
        this.elementData = new Object[initialCapacity];
    }
将当前容量值设置为 实际元素个数
    public void trimToSize() {
        modCount++;
        if (size < elementData.length) {
            elementData = Arrays.copyOf(elementData, size);
        }
    }
确定ArrayList容量,如果容量不足以容纳所有的元素,则设置 新容量=1.5旧容量

    public void ensureCapacity(int minCapacity) {	//1.7改为向外部提供的方法
        int minExpand = (elementData != EMPTY_ELEMENTDATA)	//是否使用的是(用于空实例的共享空数组实例)
           
            ? 0: DEFAULT_CAPACITY;			//0:10

        if (minCapacity > minExpand) {			
            ensureExplicitCapacity(minCapacity);
        }
    }
    private void ensureCapacityInternal(int minCapacity) {
        if (elementData == EMPTY_ELEMENTDATA) {		//如果底层数组是空数组示例。
            minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
        }

        ensureExplicitCapacity(minCapacity);
    }
    private void ensureExplicitCapacity(int minCapacity) {
        modCount++;

        // overflow-conscious code
        if (minCapacity - elementData.length > 0)		//如果最小需要的容量>当前数组长度
            grow(minCapacity);				//扩张
    }
    private void grow(int minCapacity) {
        // overflow-conscious code
        int oldCapacity = elementData.length;
        int newCapacity = oldCapacity + (oldCapacity >> 1);
        if (newCapacity - minCapacity < 0)		
            newCapacity = minCapacity;
        if (newCapacity - MAX_ARRAY_SIZE > 0)
            newCapacity = hugeCapacity(minCapacity);	//设置新的容量,该函数中设置newCapacity = Integer.Max_Value
        // minCapacity is usually close to size, so this is a win:
        elementData = Arrays.copyOf(elementData, newCapacity);
    }
indexOf,lastIndexOf确定元素在ArrayList存在的第一个的位置,都通过elementData[i]确定

    public int indexOf(Object o) {
        if (o == null) {
            for (int i = 0; i < size; i++)
                if (elementData[i]==null)
                    return i;
        } else {
            for (int i = 0; i < size; i++)
                if (o.equals(elementData[i]))
                    return i;
        }
        return -1;
    }
克隆

    public Object clone() {
        try {
            @SuppressWarnings("unchecked")
                ArrayList<E> v = (ArrayList<E>) super.clone();
            v.elementData = Arrays.copyOf(elementData, size);//将全部元素拷贝进去
            v.modCount = 0;
            return v;
        } catch (CloneNotSupportedException e) {
            // this shouldn't happen, since we are Cloneable
            throw new InternalError();
        }
    }
在该类中存在两种toArray(), 当我们调用ArrayList中的  toArray() ,可能遇到过抛出“ java.lang.ClassCastException ”异常的情况。

    public Object[] toArray() {		//返回Obejct[]
        return Arrays.copyOf(elementData, size);
    }
    @SuppressWarnings("unchecked")
    public <T> T[] toArray(T[] a) {		//返回模版数组
        if (a.length < size) //则新建一个T[]数组,数组大小是“ArrayList的元素个数”,并将“ArrayList”全部拷贝到新数组中
            return (T[]) Arrays.copyOf(elementData, size, a.getClass());
        System.arraycopy(elementData, 0, a, 0, size);  //大于,则将数组拷贝到a中
        if (a.length > size)
            a[size] = null;
        return a;
    }
    @SuppressWarnings("unchecked")
    E elementData(int index) {	//包内访问,咱本类中get,set,remove会调用
        return (E) elementData[index];
    }

调用 toArray() 函数会抛出“java.lang.ClassCastException”异常,但是调用 toArray(T[] contents) 能正常返回 T[]。toArray() 会抛出异常是因为 toArray() 返回的是 Object[] 数组,将 Object[] 转换为其它类型(如如,将Object[]转换为的Integer[])则会抛出“java.lang.ClassCastException”异常,因为Java不支持向下转型。具体的可以参考前面ArrayList.java的源码介绍部分的toArray()。

解决该问题的办法是调用 <T> T[] toArray(T[] contents) , 而不是 Object[] toArray()。

调用 toArray(T[] contents) 返回T[]的可以通过以下几种方式实现。

// toArray(T[] contents)调用方式一
public static Integer[] vectorToArray1(ArrayList<Integer> v) {
    Integer[] newText = new Integer[v.size()];
    v.toArray(newText);
    return newText;
}

// toArray(T[] contents)调用方式二。最常用!
public static Integer[] vectorToArray2(ArrayList<Integer> v) {
    Integer[] newText = (Integer[])v.toArray(new Integer[0]);
    return newText;
}

// toArray(T[] contents)调用方式三
public static Integer[] vectorToArray3(ArrayList<Integer> v) {
    Integer[] newText = new Integer[v.size()];
    Integer[] newStrings = (Integer[])v.toArray(newText);
    return newStrings;
}

get,set

    public E get(int index) {
        rangeCheck(index);	//判断index>=size? 大于则IndexOutOfBoundsException
        return elementData(index);
    }
    public E set(int index, E element) {
        rangeCheck(index);
        E oldValue = elementData(index);
        elementData[index] = element;
        return oldValue;
    }
add

    public boolean add(E e) {
        ensureCapacityInternal(size + 1);  // 判断扩容。另外 最初数组是空的,add调用该方法,在之后空数组示例会扩容

        elementData[size++] = e;	//末位添加元素
        return true;
    }
    public void add(int index, E element) {	//Index位置添加,即将Index位置后面的元素全后移一位
        rangeCheckForAdd(index);		//判断 >size  <0

        ensureCapacityInternal(size + 1);  // 调用它还会mountCount++
        System.arraycopy(elementData, index, elementData, index + 1,
                         size - index);
        elementData[index] = element;
        size++;
    }
remove 分别有删除指定元素和删除指定位置元素

    public E remove(int index) {
        rangeCheck(index);

        modCount++;
        E oldValue = elementData(index);

        int numMoved = size - index - 1;
        if (numMoved > 0)
            System.arraycopy(elementData, index+1, elementData, index,
                             numMoved);
        elementData[--size] = null; // clear to let GC do its work

        return oldValue;
    }
    public boolean remove(Object o) {
        if (o == null) {
            for (int index = 0; index < size; index++)
                if (elementData[index] == null) {
                    fastRemove(index);
                    return true;
                }
        } else {
            for (int index = 0; index < size; index++)
                if (o.equals(elementData[index])) {
                    fastRemove(index);
                    return true;
                }
        }
        return false;
    }
    private void fastRemove(int index) {
        modCount++;
        int numMoved = size - index - 1;
        if (numMoved > 0)
            System.arraycopy(elementData, index+1, elementData, index,
                             numMoved);
        elementData[--size] = null; // clear to let GC do its work
    }
clear清空

    public void clear() {
        modCount++;

        // clear to let GC do its work
        for (int i = 0; i < size; i++)
            elementData[i] = null;

        size = 0;
    }
addAll增加集合元素

    public boolean addAll(Collection<? extends E> c) {
        Object[] a = c.toArray();	//转成数组
        int numNew = a.length;
        ensureCapacityInternal(size + numNew);  // Increments modCount
        System.arraycopy(a, 0, elementData, size, numNew);	//源数组。源数组起复位置。目的数组,起始位置,长度
        size += numNew;
        return numNew != 0;
    }
    public boolean addAll(int index, Collection<? extends E> c) {
        rangeCheckForAdd(index);

        Object[] a = c.toArray();
        int numNew = a.length;
        ensureCapacityInternal(size + numNew);  // Increments modCount

        int numMoved = size - index;
        if (numMoved > 0)
            System.arraycopy(elementData, index, elementData, index + numNew,
                             numMoved);

        System.arraycopy(a, 0, elementData, index, numNew);
        size += numNew;
        return numNew != 0;
    }
删除指定范围元素

    protected void removeRange(int fromIndex, int toIndex) {
        modCount++;
        int numMoved = size - toIndex;
        System.arraycopy(elementData, toIndex, elementData, fromIndex,
                         numMoved);
        int newSize = size - (toIndex-fromIndex);
        for (int i = newSize; i < size; i++) {
            elementData[i] = null;
        }
        size = newSize;
    }

移除全部

    public boolean removeAll(Collection<?> c) {	//从本类中移除与c集合元素相同的元素
        return batchRemove(c, false);
    }
    public boolean retainAll(Collection<?> c) {	//保留和c相同的元素
        return batchRemove(c, true);
    }
    private boolean batchRemove(Collection<?> c, boolean complement) {
        final Object[] elementData = this.elementData;
        int r = 0, w = 0;	//r用于向后遍历elementData,w用于等待覆盖保存元素
        boolean modified = false;
        try {
            for (; r < size; r++)
                if (c.contains(elementData[r]) == complement)//根据complement是true还是false选择保存或者删除
                    elementData[w++] = elementData[r];
        } finally {
            //发生异常把r后面的元素复制到w后面
            if (r != size) {
                System.arraycopy(elementData, r,
                                 elementData, w,
                                 size - r);
                w += size - r;
            }
            if (w != size) {
                // 移除多余的元素
                for (int i = w; i < size; i++)
                    elementData[i] = null;
                modCount += size - w;
                size = w;
                modified = true;
            }
        }
        return modified;
    }
java.io.Serializable的写入函数,将容量和所有元素值写入输出流
    private void writeObject(java.io.ObjectOutputStream s)
        throws java.io.IOException{
        
        int expectedModCount = modCount;
        s.defaultWriteObject();		//使用默认的机制去写入对象的非transient部分

        s.writeInt(size);		//写入数组容量

        for (int i=0; i<size; i++) {		//所有元素值写入
            s.writeObject(elementData[i]);
        }

        if (modCount != expectedModCount) {
            throw new ConcurrentModificationException();
        }
    }
java.io.Serializable的读取函数。先读size在读所有元素值 ------------------这里为什么size直接就有数据?是不是因为size直接反序列化出来了?

    private void readObject(java.io.ObjectInputStream s)
        throws java.io.IOException, ClassNotFoundException {
        elementData = EMPTY_ELEMENTDATA;

        s.defaultReadObject();

        // Read in capacity
        s.readInt(); // ignored

        if (size > 0) {
            // be like clone(), allocate array based upon size not capacity
            ensureCapacityInternal(size);

            Object[] a = elementData;
            // Read in all elements in the proper order.
            for (int i=0; i<size; i++) {
                a[i] = s.readObject();
            }
        }
    }
获取两种迭代器

    public ListIterator<E> listIterator(int index) {
        if (index < 0 || index > size)
            throw new IndexOutOfBoundsException("Index: "+index);
        return new ListItr(index);
    }
    public ListIterator<E> listIterator() {
        return new ListItr(0);
    }
    public Iterator<E> iterator() {
        return new Itr();
    }
Itr和ListItr在ArrayList有实现,方法和AbstractLsit相似。

三种ArrayList遍历方式:

(1)迭代器遍历

Integer value = null;
Iterator iter = list.iterator();
while (iter.hasNext()) {
    value = (Integer)iter.next();
}

(2)随机访问(最快)

Integer value = null;
int size = list.size();
for (int i=0; i<size; i++) {
    value = (Integer)list.get(i);        
}

(3)foreach

Integer value = null;
for (Integer integ:list) {
    value = integ;
}



















  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值