源码来自JDK8
List接口
public interface List<E> extends Collection<E> {
}
ArrayList
public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess
, Cloneable
, java
.io
.Serializable
{
private static final int DEFAULT_CAPACITY
= 10;
private static final Object
[] EMPTY_ELEMENTDATA
= {};
private static final Object
[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA
= {};
transient Object
[] elementData
;
public ArrayList() {
this.elementData
= DEFAULTCAPACITY_EMPTY_ELEMENTDATA
;
}
public boolean add(E e
) {
ensureCapacityInternal(size
+ 1);
elementData
[size
++] = e
;
return true;
}
private void ensureCapacityInternal(int minCapacity
) {
ensureExplicitCapacity(calculateCapacity(elementData
, minCapacity
));
}
private static int calculateCapacity(Object
[] elementData
, int minCapacity
) {
if (elementData
== DEFAULTCAPACITY_EMPTY_ELEMENTDATA
) {
return Math
.max(DEFAULT_CAPACITY
, minCapacity
);
}
return minCapacity
;
}
private void ensureExplicitCapacity(int minCapacity
) {
modCount
++;
if (minCapacity
- elementData
.length
> 0)
grow(minCapacity
);
}
private void grow(int minCapacity
) {
int oldCapacity
= elementData
.length
;
int newCapacity
= oldCapacity
+ (oldCapacity
>> 1);
if (newCapacity
- minCapacity
< 0)
newCapacity
= minCapacity
;
if (newCapacity
- MAX_ARRAY_SIZE
> 0)
newCapacity
= hugeCapacity(minCapacity
);
elementData
= Arrays
.copyOf(elementData
, newCapacity
);
}
private static int hugeCapacity(int minCapacity
) {
if (minCapacity
< 0)
throw new OutOfMemoryError();
return (minCapacity
> MAX_ARRAY_SIZE
) ?
Integer
.MAX_VALUE
:
MAX_ARRAY_SIZE
;
}
}
LinkedList
public class LinkedList<E> extends AbstractSequentialList<E> implements List<E>, Deque
<E>, Cloneable
, java
.io
.Serializable
{
transient Node
<E> first
;
transient Node
<E> last
;
public LinkedList() {
}
}