您的位置:首页 > 编程语言 > Java开发

java ArrayList 源码解析(jdk1.6)

2014-03-17 15:07 543 查看
 加油!

 本文简单介绍java中ArrayList内部的结构及实现原理,以便更好的、高效的使用它。

  ArrayList 是实现了Collection 和list 接口的集合,实质上是一个会自动增长的数组。查询效率比较高,增删的效率比较低,适用于查询比较频繁,增删动作比较少的元素管理的集合。

我们可以通过几个问题来细看ArrayList

1、什么组成了ArrayList,它的‘血肉’?

2、怎么实现一个ArrayList对象?

3、ArrayList集合怎么实现增删改查?

首先看ArrayList的‘血肉’:

  ArrayList是传说中的动态的数组,它只定义了类两个私有属性

   /**
* The array buffer into which the elements of the ArrayList are stored.
* The capacity of the ArrayList is the length of this array buffer.
*/
private transient Object[] elementData;

/**
* The size of the ArrayList (the number of elements it contains).
*
* @serial
*/
private int size;显然,elementData存储ArrayList的元素,size表示它包含的元素的数量。
ArrayList提供了三个构造方法,来实现ArrayList 对象,

/**
* Constructs an empty list with the specified initial capacity.
*
* @param initialCapacity the initial capacity of the list
* @exception IllegalArgumentException if the specified initial capacity
* is negative
*/
public ArrayList(int initialCapacity) {
super();
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
this.elementData = new Object[initialCapacity];
}

/**
* Constructs an empty list with an initial capacity of ten.
*/
public ArrayList() {
this(10);
}

/**
* Constructs a list containing the elements of the specified
* collection, in the order they are returned by the collection's
* iterator.
*
* @param c the collection whose elements are to be placed into this list
* @throws NullPointerException if the specified collection is null
*/
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);
}
  第一个构造器提供一个 initialCapacity,来初始化elementData数组的大小,第二个构造器调用 第一个构造器并传入参数10,默认 数组大小为10,第三个构造器提供一个集合初始化elementData数组

再来看ArrayList 怎么实现增删改查

  add(E e) :在集合的尾部增加一个元素,

  /**
* Appends the specified element to the end of this list.
*
* @param e element to be appended to this list
* @return <tt>true</tt> (as specified by {@link Collection#add})
*/
public boolean add(E e) {
ensureCapacity(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}可看到add方法中有一个ensureCapacity(size+1);看方法名就知道是确保数组容量够用的,现在看一个这个方法是怎么实现的
/**
* Increases the capacity of this <tt>ArrayList</tt> instance, if
* necessary, to ensure that it can hold at least the number of elements
* specified by the minimum capacity argument.
*
* @param minCapacity the desired minimum capacity
*/
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);
}
}
可看到ensureCapacity()方法至少使elementData的容量加1,所以elementData[size]不会出现越界的情况,
但您可以注意的容量的扩展是靠数组元素的复制,多次扩容数组会影响运行速度,所以最后不要多次扩充数组的容量。

另外增加方法还有add(int index, E element)

/**
* Inserts the specified element at the specified position in this
* list. Shifts the element currently at that position (if any) and
* any subsequent elements to the right (adds one to their indices).
*
* @param index index at which the specified element is to be inserted
* @param element element to be inserted
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
public void add(int index, E element) {
if (index > size || index < 0)
throw new IndexOutOfBoundsException(
"Index: "+index+", Size: "+size);

ensureCapacity(size+1); // Increments modCount!!
System.arraycopy(elementData, index, elementData, index + 1,
size - index);
elementData[index] = element;
size++;
}

addAll(Collection<? extends E> c)
/**
* Appends all of the elements in the specified collection to the end of
* this list, in the order that they are returned by the
* specified collection's Iterator. The behavior of this operation is
* undefined if the specified collection is modified while the operation
* is in progress. (This implies that the behavior of this call is
* undefined if the specified collection is this list, and this
* list is nonempty.)
*
* @param c collection containing elements to be added to this list
* @return <tt>true</tt> if this list changed as a result of the call
* @throws NullPointerException if the specified collection is null
*/
public boolean addAll(Collection<? extends E> c) {
Object[] a = c.toArray();
int numNew = a.length;
ensureCapacity(size + numNew); // Increments modCount
System.arraycopy(a, 0, elementData, size, numNew);
size += numNew;
return numNew != 0;
}ArrayList 删除方法:E remove(int index);
  public E remove(int index) {
RangeCheck(index);

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

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

return oldValue;
}

boolean remove(Object o);
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;
}从这个可以看出ArrayList可以存储null类型
修改ArrayList中的元素E set(int index,E element);

public E set(int index, E element) {
RangeCheck(index);

E oldValue = (E) elementData[index];
elementData[index] = element;
return oldValue;
}ArrayList中的查找:E get(int index);
public E get(int index) {
RangeCheck(index);

return (E) elementData[index];
}

其中RangeCheck(index);方法是检查一个是不是超出数组界限了,
private void RangeCheck(int index) {
if (index >= size)
throw new IndexOutOfBoundsException(
"Index: "+index+", Size: "+size);
}

 

  


                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: