ArrayList源代码分析

ArrayList源代码分析
在util包内
package java.util;

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

属性:
private transient Object[] elementData;   //对象数组
private int size;                         //长度   

方法:
//构造方法
public ArrayList(int initialCapacity) {  //initialCapacity为初始分配容量
	super();  //父类实现 为空方法
       if (initialCapacity < 0)   //正数判断
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
	this.elementData = new Object[initialCapacity];   //分配数组
    }

public ArrayList() {
	this(10);   //无参构造方法,带10个容量
    }

 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 void trimToSize() {  //将此 ArrayList 实例的容量调整为列表的当前大小。
	modCount++;  
	int oldCapacity = elementData.length;
	if (size < oldCapacity) {
            elementData = Arrays.copyOf(elementData, size);
	}
    }





调整容量大小
public void ensureCapacity(int minCapacity) {
	modCount++;
	int oldCapacity = elementData.length;
	if (minCapacity > oldCapacity) {
	    Object oldData[] = elementData;
	    int newCapacity = (oldCapacity * 3)/2 + 1;
    	    if (newCapacity < minCapacity)
		newCapacity = minCapacity;
            // minCapacity is usually close to size, so this is a win:
            elementData = Arrays.copyOf(elementData, newCapacity);
	}
    }

返回容量大小
 public int size() {
	return size;
    }

判断是否为空
public boolean isEmpty() {
	return size == 0;
    }

是否包含元素
 public boolean contains(Object o) {
	return indexOf(o) >= 0;
    }

查找第一个相同元素的位置
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;             //找不到返回-1
    }

查找最后一个相同元素的位置
 public int lastIndexOf(Object o) {
	if (o == null) {                  //如果为空
	    for (int i = size-1; i >= 0; i--)  //遍历数组
		if (elementData[i]==null)
		    return i;
	} else {
	    for (int i = size-1; i >= 0; i--)  //遍历数组
		if (o.equals(elementData[i]))
		    return i;
	}
	return -1;                      //找不到返回-1
    }


你可能感兴趣的:(java,C++,c,C#)