ArrayList
属性
Object[] elementData; // 元素数组
int size; // 元素个数
Object[] EMPTY_ELEMENTDATA = {}; // initialCapacity=0
Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {}; // 未指定initialCapacity
int DEFAULT_CAPACITY = 10;
int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8; // 防止对象size超JVM限制
普通方法
// 遍历elementData:从0开始,返回第一个匹配项(equals);o是null,返回第一个null索引;命中失败,返回-1
public int indexOf(Object o)
// 从size-1开始
public int lastIndexOf(Object o)
// indexOf(o) >= 0
public boolean contains(Object o)
// 更新,返旧;index不对抛异常
public E set(int index, E element)
// modCound++,elementData置空,size归0
public void clear()
// 序列化
private void readObject(java.io.ObjectInputStream s)
private void writeObject(java.io.ObjectOutputStream s)
添加元素
// 默认末尾添加
public boolean add(E e) {
ensureCapacityInternal(size + 1);
elementData[size++] = e;
return true;
}
// 索引添加
public void add(int index, E element) {
rangeCheckForAdd(index); // 可以等于size
ensureCapacityInternal(size + 1);
System.arraycopy(elementData, index, elementData, index + 1, size - index);
elementData[index] = element;
size++;
}
// 批量末尾
public boolean addAll(Collection extends E> c) {
Object[] a = c.toArray();
int numNew = a.length;
ensureCapacityInternal(size + numNew);
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);
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;
}
扩容
// add,addAll,readObject调用
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;
}
// 外部调用
public void ensureCapacity(int minCapacity) {
int minExpand = (elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA) ? 0 : DEFAULT_CAPACITY;
if (minCapacity > minExpand) {
ensureExplicitCapacity(minCapacity);
}
}
// 手动缩减elementData至size,采用Arrays.copyOf
public void trimToSize()
查找
// 灰常灰常快,对泛型做了主动转型
public E get(int index) {
rangeCheck(index); // 竟然没查index < 0,不过也无所谓,后面还是会报错
return elementData(index);
}
@SuppressWarnings("unchecked")
E elementData(int index) {
return (E) elementData[index];
}
删除
- 不调整elementData,trimToSize可手动压缩
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;
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;
}
// 集合碰撞删除
public boolean removeAll(Collection> c) {
Objects.requireNonNull(c);
return batchRemove(c, false);
}
// 集合碰撞保留
public boolean retainAll(Collection> c) {
Objects.requireNonNull(c);
return batchRemove(c, true);
}
private boolean batchRemove(Collection> c, boolean complement)
...
// false,碰撞移除;true,碰撞保留
if (c.contains(elementData[r]) == complement)
elementData[w++] = elementData[r];
// 不出异常的话,只要把w后面剩余的全部置空即可
其它方法
// 浅拷贝之外,需拷贝elementData,并将modCount置0
public Object clone() {
try {
ArrayList> v = (ArrayList>) super.clone();
v.elementData = Arrays.copyOf(elementData, size);
v.modCount = 0;
return v;
} catch (CloneNotSupportedException e) {
throw new InternalError(e);
}
}
public Object[] toArray() {
return Arrays.copyOf(elementData, size);
}
@SuppressWarnings("unchecked")
public T[] toArray(T[] a) {
if (a.length < size)
return (T[]) Arrays.copyOf(elementData, size, a.getClass());
System.arraycopy(elementData, 0, a, 0, size);
if (a.length > size)
a[size] = null;
return a;
}
LinkedList - 双向链表
属性
int size = 0; // why transient
Node first;
Node last;
int modCount = 0;
Node
private static class Node {
Node prev;
E item;
Node next;
Node(Node prev, E element, Node next) {
this.item = element;
this.next = next;
this.prev = prev;
}
}
普通方法
// 索引定位Node,根据index大小分前后
Node node(int index) {
// assert isElementIndex(index);
if (index < (size >> 1)) {
Node x = first;
for (int i = 0; i < index; i++)
x = x.next;
return x;
} else {
Node x = last;
for (int i = size - 1; i > index; i--)
x = x.prev;
return x;
}
}
public int indexOf(Object o) {
int index = 0;
if (o == null) {
for (Node x = first; x != null; x = x.next) {
if (x.item == null)
return index;
index++;
}
} else {
for (Node x = first; x != null; x = x.next) {
if (o.equals(x.item))
return index;
index++;
}
}
return -1;
}
public int lastIndexOf(Object o) {
int index = size;
if (o == null) {
for (Node x = last; x != null; x = x.prev) {
index--;
if (x.item == null)
return index;
}
} else {
for (Node x = last; x != null; x = x.prev) {
index--;
if (o.equals(x.item))
return index;
}
}
return -1;
}
public boolean contains(Object o) {
return indexOf(o) != -1;
}
public E set(int index, E element) {
checkElementIndex(index);
Node x = node(index);
E oldVal = x.item;
x.item = element;
return oldVal;
}
public void clear() {
for (Node x = first; x != null; ) {
Node next = x.next;
x.item = null;
x.next = null;
x.prev = null;
x = next;
}
first = last = null;
size = 0;
modCount++;
}
// 序列化
private void readObject(java.io.ObjectInputStream s)
private void writeObject(java.io.ObjectOutputStream s)
添加
// 默认末尾添加
public boolean add(E e) {
linkLast(e);
return true;
}
void linkLast(E e) {
final Node l = last;
final Node newNode = new Node<>(l, e, null);
last = newNode;
if (l == null)
first = newNode;
else
l.next = newNode;
size++;
modCount++;
}
// 索引添加
public void add(int index, E element) {
checkPositionIndex(index);
if (index == size)
linkLast(element);
else
linkBefore(element, node(index));
}
void linkBefore(E e, Node succ) {
// assert succ != null;
final Node pred = succ.prev;
final Node newNode = new Node<>(pred, e, succ);
succ.prev = newNode;
if (pred == null)
first = newNode;
else
pred.next = newNode;
size++;
modCount++;
}
public void addFirst(E e) // linkFirst
public void addLast(E e) // linkLast
public boolean addAll(Collection extends E> c) // addAll(size, c)
public boolean addAll(int index, Collection extends E> c)
checkPositionIndex(index);
Object[] a = c.toArray();
succ = node(index);
// 遍历a,从succ开始,按序往后插入
size += a.length;
modCount++; //mod只算一次
查找
public E get(int index) {
checkElementIndex(index);
return node(index).item;
}
public E getFirst() //first为空,抛NoSuchElementException
public E getLast() //last为空,抛NoSuchElementException
删除
public E remove(int index) {
checkElementIndex(index);
return unlink(node(index));
}
public boolean remove(Object o) {
if (o == null) {
for (Node x = first; x != null; x = x.next) {
if (x.item == null) {
unlink(x);
return true;
}
}
} else {
for (Node x = first; x != null; x = x.next) {
if (o.equals(x.item)) {
unlink(x);
return true;
}
}
}
return false;
}
E unlink(Node x) // 将Node前后连在一起
public E removeFirst() // unlinkFirst
public E removeLast() // unlinkLast
private E unlinkFirst(Node f)
private E unlinkLast(Node l)
获取添加集锦
public E peek() // 返first,为空返null
public E peekFirst() // 返first,为空返null
public E peekLast() // 返last,为空返null
public E element() // 返first,为空抛异常
public E poll() // 删除返first,为空返null
public E pollFirst() // 删除返first,为空返null
public E pollLast() // 删除返last,为空返null
public E pop() // 删除返first,为空抛异常
public E remove() // 删除返first,为空抛异常
public void push(E e) // linkFirst(e)
public boolean offer(E e) // linkLast(e)
public boolean offerFirst(E e) // linkFirst(e)
public boolean offerLast(E e) // linkLast(e)
public boolean removeFirstOccurrence(Object o) // 删除从first开始的第一匹配项
public boolean removeLastOccurrence(Object o) // 删除从last开始的第一匹配项
其它方法
public Object clone() {
LinkedList clone = superClone();
// Put clone into "virgin" state
clone.first = clone.last = null;
clone.size = 0;
clone.modCount = 0;
// Initialize clone with our elements
for (Node x = first; x != null; x = x.next)
clone.add(x.item);
return clone;
}
public Object[] toArray() {
Object[] result = new Object[size];
int i = 0;
for (Node x = first; x != null; x = x.next)
result[i++] = x.item;
return result;
}
@SuppressWarnings("unchecked")
public T[] toArray(T[] a) {
if (a.length < size)
a = (T[])java.lang.reflect.Array.newInstance(a.getClass().getComponentType(), size);
int i = 0;
Object[] result = a;
for (Node x = first; x != null; x = x.next)
result[i++] = x.item;
if (a.length > size)
a[size] = null;
return a;
}