public interface Iterable<T> {
Iterator<T> iterator();
}
public interface Collection<E> extends Iterable<E> {
int size();
boolean isEmpty();
boolean contains(Object o);
Object[] toArray();
<T> T[] toArray(T[] a);
boolean add(E e);
boolean remove(Object o);
boolean containsAll(Collection<?> c);
boolean addAll(Collection<? extends E> c);
boolean removeAll(Collection<?> c);
boolean retainAll(Collection<?> c);
void clear();
boolean equals(Object o);
int hashCode();
}
public interface List<E> extends Collection<E> {
E get(int index);
E set(int index, E element);
void add(int index, E element);
E remove(int index);
int indexOf(Object o);
int lastIndexOf(Object o);
ListIterator<E> listIterator();
ListIterator<E> listIterator(int index);
List<E> subList(int fromIndex, int toIndex);
}
//可变数组,有序
public class ArrayList<E> extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{
private static final long serialVersionUID = 8683452581122892189L;
private transient Object[] elementData;//数组数据
private int size;//大小
public ArrayList(int initialCapacity) {//指定数量创建可变数组
super();
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
this.elementData = new Object[initialCapacity];//初始化数据
}
public ArrayList() {//默认创建10个大小的数据
this(10);
}
public ArrayList(Collection<? extends E> c) {
elementData = c.toArray();//初始化数据根据传进来的集合C
size = elementData.length;//初始化大小
//如果elementData不是Object[],则复制一个新的???这里什么时候会导致两者不等呢?
if (elementData.getClass() != Object[].class)
elementData = Arrays.copyOf(elementData, size, Object[].class);
}
public void trimToSize() {
modCount++;//版本号加1
int oldCapacity = elementData.length;//当前数组中的大小
if (size < oldCapacity) {//如果目前的大小小于数组的大小,那么将数组大小调整为size大小,节省内存空间
elementData = Arrays.copyOf(elementData, size);
}
}
public void ensureCapacity(int minCapacity) {
modCount++;//版本号加1
int oldCapacity = elementData.length;//当前数组中的大小
if (minCapacity > oldCapacity) {//如果传进来的大小大于当前数组中的大小,扩充它
Object oldData[] = elementData;
int newCapacity = (oldCapacity * 3)/2 + 1;//扩充为原大小的1.5倍加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;//如果包含了o,则indexOf返回的大小肯定大于或等于0
}
public int indexOf(Object o) {
//数组中存在o,则返回它所在位置的索引,否则返回-1
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 int lastIndexOf(Object o) {
//找出o在数组中最后出现的索引,找到返回索引,否则返回-1
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;
}
public Object clone() {
try {
ArrayList<E> v = (ArrayList<E>) super.clone();
v.elementData = Arrays.copyOf(elementData, size);//拷贝数据
v.modCount = 0;//设置初始化版本为0
return v;
} catch (CloneNotSupportedException e) {
// this shouldn't happen, since we are Cloneable
throw new InternalError();
}
}
public Object[] toArray() {
return Arrays.copyOf(elementData, size);//返回拷贝数组
}
public <T> T[] toArray(T[] a) {
//返回包含此列表中所有元素的数组;返回数组的运行时类型是指定数组的运行时类型。
if (a.length < size)
// Make a new array of a's runtime type, but my contents:
return (T[]) Arrays.copyOf(elementData, size, a.getClass());
System.arraycopy(elementData, 0, a, 0, size);
if (a.length > size)
a[size] = null;
return a;
}
public E get(int index) {
RangeCheck(index);//检查越界
return (E) elementData[index];//返回指定类型的数据
}
public E set(int index, E element) {
RangeCheck(index);//检查越界
//覆盖旧数据,并返回旧数据
E oldValue = (E) elementData[index];
elementData[index] = element;
return oldValue;
}
public boolean add(E e) {
ensureCapacity(size + 1);//版本号会加1,不够增加1.5加1
elementData[size++] = e;
return true;
}
public void add(int index, E element) {
if (index > size || index < 0)//数组是否越界
throw new IndexOutOfBoundsException(
"Index: "+index+", Size: "+size);
ensureCapacity(size+1); //版本号会加1,不够增加1.5加1
System.arraycopy(elementData, index, elementData, index + 1,
size - index);//更新数组中数据的位置(将elementData中的[index, size - index) 个数据拷贝到elementData中的index+1的位置)
elementData[index] = element;
size++;
}
public E remove(int index) {
RangeCheck(index);//检查越界
modCount++;//版本号加1
E oldValue = (E) 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) {
//找到删除并返回true,否则返回false
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) {
//remove方法简略版
modCount++;
int numMoved = size - index - 1;
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
elementData[--size] = null; // Let gc do its work
}
public void clear() {
//清空
modCount++;
// Let gc do its work
for (int i = 0; i < size; i++)
elementData[i] = null;
size = 0;
}
public boolean addAll(Collection<? extends E> c) {
//按照指定 collection 的迭代器所返回的元素顺序,将该 collection 中的所有元素添加到此列表的尾部。
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;
}
public boolean addAll(int index, Collection<? extends E> c) {
//从指定的位置开始,将指定 collection 中的所有元素插入到此列表中。
if (index > size || index < 0)
throw new IndexOutOfBoundsException(
"Index: " + index + ", Size: " + size);
Object[] a = c.toArray();
int numNew = a.length;
ensureCapacity(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) {
//移除列表中索引在 fromIndex(包括)和 toIndex(不包括)之间的所有元素。
modCount++;
int numMoved = size - toIndex;
System.arraycopy(elementData, toIndex, elementData, fromIndex,
numMoved);
// Let gc do its work
int newSize = size - (toIndex-fromIndex);
while (size != newSize)
elementData[--size] = null;
}
private void RangeCheck(int index) {
if (index >= size)//判断数据是否越界
throw new IndexOutOfBoundsException(
"Index: "+index+", Size: "+size);
}
private void writeObject(java.io.ObjectOutputStream s)
throws java.io.IOException{
// Write out element count, and any hidden stuff
int expectedModCount = modCount;
s.defaultWriteObject();
// Write out array length
s.writeInt(elementData.length);//写数组大小,不是数据大小
// Write out all elements in the proper order.
for (int i=0; i<size; i++)//写对象
s.writeObject(elementData[i]);
if (modCount != expectedModCount) {//在写的过程中版本号被修改时(增,删操作)抛异常
throw new ConcurrentModificationException();
}
}
private void readObject(java.io.ObjectInputStream s)
throws java.io.IOException, ClassNotFoundException {
// Read in size, and any hidden stuff
s.defaultReadObject();
// Read in array length and allocate array
int arrayLength = s.readInt();//读数组大小
Object[] a = elementData = new Object[arrayLength];//根据大小构建数组
// Read in all elements in the proper order.
for (int i=0; i<size; i++)//给数组赋值
a[i] = s.readObject();
}
}
private class Itr implements Iterator<E> {
int cursor = 0;//游标
int lastRet = -1;//游标最后指向的地方
int expectedModCount = modCount;//期望的版本号
public boolean hasNext() {//当游标与数组中数据容量大小不等时说明有下一个数据
return cursor != size();
}
public E next() {
checkForComodification();//检查版本号
try {
E next = get(cursor);//获取元素
lastRet = cursor++;//把游标赋给lastRet,然后游标自增,准备指向下一个数据
return next;
} catch (IndexOutOfBoundsException e) {
checkForComodification();
throw new NoSuchElementException();
}
}
public void remove() {
if (lastRet == -1)
throw new IllegalStateException();
checkForComodification();//检查版本号
try {
AbstractList.this.remove(lastRet);//根据索引移除数据
if (lastRet < cursor)
cursor--;
lastRet = -1;
expectedModCount = modCount;//期望的版本号更新最新的版本号
} catch (IndexOutOfBoundsException e) {
throw new ConcurrentModificationException();
}
}
final void checkForComodification() {
if (modCount != expectedModCount)//期望的版本号与当前的版本号不等,抛异常
throw new ConcurrentModificationException();
}
}
private class ListItr extends Itr implements ListIterator<E> {
ListItr(int index) {
cursor = index;
}
public boolean hasPrevious() {
return cursor != 0;
}
public E previous() {
checkForComodification();
try {
int i = cursor - 1;
E previous = get(i);
lastRet = cursor = i;
return previous;
} catch (IndexOutOfBoundsException e) {
checkForComodification();
throw new NoSuchElementException();
}
}
public int nextIndex() {
return cursor;
}
public int previousIndex() {
return cursor-1;
}
public void set(E e) {
if (lastRet == -1)
throw new IllegalStateException();
checkForComodification();
try {
AbstractList.this.set(lastRet, e);
expectedModCount = modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
public void add(E e) {
checkForComodification();
try {
AbstractList.this.add(cursor++, e);
lastRet = -1;
expectedModCount = modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
}
public class LinkedList<E>
extends AbstractSequentialList<E>
implements List<E>, Deque<E>, Cloneable, java.io.Serializable
{
private transient Entry<E> header = new Entry<E>(null, null, null);//内部用一个Entry来维护双向链表
private transient int size = 0;//大小
public LinkedList() {
header.next = header.previous = header;//初始化使头部和尾部都指向自己
}
public LinkedList(Collection<? extends E> c) {
this();//调用默认构造方法
addAll(c);//把集合的内容加入到链表尾部
}
public E getFirst() {
if (size==0)//如果大小为0,抛异常
throw new NoSuchElementException();
return header.next.element;//返回头部所指向的下一个数据,上一个数据为空
}
public E getLast() {
if (size==0)//如果大小为0,抛异常
throw new NoSuchElementException();
return header.previous.element;//返回头部所指向上一个数据,下一个数据为空
}
public E removeFirst() {
return remove(header.next);//移除第一个数据
}
public E removeLast() {
return remove(header.previous);//移除最后一个数据
}
public void addFirst(E e) {
addBefore(e, header.next);//加到头部
}
public void addLast(E e) {
addBefore(e, header);//加到尾部
}
public boolean contains(Object o) {
return indexOf(o) != -1;//链表是否包含o
}
public int size() {
return size;//返回大小
}
public boolean add(E e) {
addBefore(e, header);//加到尾部
return true;
}
public boolean remove(Object o) {
//从链表中移除o
if (o==null) {
for (Entry<E> e = header.next; e != header; e = e.next) {
if (e.element==null) {
remove(e);
return true;
}
}
} else {
for (Entry<E> e = header.next; e != header; e = e.next) {
if (o.equals(e.element)) {
remove(e);
return true;
}
}
}
return false;
}
public boolean addAll(Collection<? extends E> c) {
return addAll(size, c);
}
public boolean addAll(int index, Collection<? extends E> c) {
if (index < 0 || index > size)
throw new IndexOutOfBoundsException("Index: "+index+
", Size: "+size);
Object[] a = c.toArray();//复制一份数组
int numNew = a.length;//数组长度
if (numNew==0)//长度为0,返回false
return false;
modCount++;//版本号加1
Entry<E> successor = (index==size ? header : entry(index));//找到指定的插入位置的Entry
Entry<E> predecessor = successor.previous;//将指定位置的上一个Entry保存起来
for (int i=0; i<numNew; i++) {
Entry<E> e = new Entry<E>((E)a[i], successor, predecessor);//构造链表数据
predecessor.next = e;//将插入指定位置前的前一个Entry的下一个指向e
predecessor = e;//插入
}
successor.previous = predecessor;//将指定位置的Entry的上一个指向被插入的最后Entry
size += numNew;//更新大小
return true;
}
public void clear() {//清空
Entry<E> e = header.next;
while (e != header) {
Entry<E> next = e.next;
e.next = e.previous = null;
e.element = null;
e = next;
}
header.next = header.previous = header;
size = 0;
modCount++;
}
public E get(int index) {
return entry(index).element;//在指定位置获取数据
}
public E set(int index, E element) {
Entry<E> e = entry(index);//找到Entry
E oldVal = e.element;//将Entry的数据保存起来
e.element = element;//覆盖新数据
return oldVal;//返回旧数据
}
public void add(int index, E element) {
addBefore(element, (index==size ? header : entry(index)));//在指定位置插入
}
public E remove(int index) {
return remove(entry(index));//在指定位置移除
}
private Entry<E> entry(int index) {
if (index < 0 || index >= size)//越界,抛异常
throw new IndexOutOfBoundsException("Index: "+index+
", Size: "+size);
Entry<E> e = header;//头部
if (index < (size >> 1)) {//如果指定位置小于大小的一半,在头部开始遍历,提高查找效率
for (int i = 0; i <= index; i++)
e = e.next;
} else {//如果指定位置小于大小的一半,在尾部开始遍历,提高查找效率
for (int i = size; i > index; i--)
e = e.previous;
}
return e;
}
public int indexOf(Object o) {
//判断o是否存在链表中,找到,返回索引,否则返回-1
int index = 0;
if (o==null) {
for (Entry e = header.next; e != header; e = e.next) {
if (e.element==null)
return index;
index++;
}
} else {
for (Entry e = header.next; e != header; e = e.next) {
if (o.equals(e.element))
return index;
index++;
}
}
return -1;
}
public int lastIndexOf(Object o) {
//判断o在链表中最后出现的位置,找到,返回索引,否则返回-1(回朔查找)
int index = size;
if (o==null) {
for (Entry e = header.previous; e != header; e = e.previous) {
index--;
if (e.element==null)
return index;
}
} else {
for (Entry e = header.previous; e != header; e = e.previous) {
index--;
if (o.equals(e.element))
return index;
}
}
return -1;
}
public E peek() {
//获取但不移除此列表的头(第一个元素)。
if (size==0)
return null;
return getFirst();
}
public E element() {
//获取但不移除此列表的头(第一个元素)。
return getFirst();
}
public E poll() {
//获取并移除此列表的头(第一个元素)
if (size==0)
return null;
return removeFirst();
}
public E remove() {
//获取并移除此列表的头(第一个元素)。
return removeFirst();
}
public boolean offer(E e) {
//将指定元素添加到此列表的末尾(最后一个元素)。
return add(e);
}
public boolean offerFirst(E e) {
//在此列表的开头插入指定的元素。
addFirst(e);
return true;
}
public boolean offerLast(E e) {
//在此列表末尾插入指定的元素。
addLast(e);
return true;
}
public E peekFirst() {
//获取但不移除此列表的第一个元素;如果此列表为空,则返回 null。
if (size==0)
return null;
return getFirst();
}
public E peekLast() {
//获取但不移除此列表的最后一个元素;如果此列表为空,则返回 null。
if (size==0)
return null;
return getLast();
}
public E pollFirst() {
//获取并移除此列表的第一个元素;如果此列表为空,则返回 null。
if (size==0)
return null;
return removeFirst();
}
public E pollLast() {
//获取并移除此列表的最后一个元素;如果此列表为空,则返回 null。
if (size==0)
return null;
return removeLast();
}
public void push(E e) {
//将元素推入此列表所表示的堆栈
addFirst(e);
}
public E pop() {
//从此列表所表示的堆栈处弹出一个元素。
return removeFirst();
}
public boolean removeFirstOccurrence(Object o) {
//从此列表中移除第一次出现的指定元素(从头部到尾部遍历列表时)。
return remove(o);
}
public boolean removeLastOccurrence(Object o) {
//从此列表中移除最后一次出现的指定元素(从头部到尾部遍历列表时)。
if (o==null) {
for (Entry<E> e = header.previous; e != header; e = e.previous) {
if (e.element==null) {
remove(e);
return true;
}
}
} else {
for (Entry<E> e = header.previous; e != header; e = e.previous) {
if (o.equals(e.element)) {
remove(e);
return true;
}
}
}
return false;
}
public ListIterator<E> listIterator(int index) {
return new ListItr(index);//返回链表迭代器
}
private class ListItr implements ListIterator<E> {
private Entry<E> lastReturned = header;//最后一次迭代出来的元素
private Entry<E> next;//下一个Entry
private int nextIndex;//下一个索引号
private int expectedModCount = modCount;//期望版本号
ListItr(int index) {//此构造方法会根据index找到Entry,并保存到next中,同时下一个索引号也跟着改变
if (index < 0 || index > size)
throw new IndexOutOfBoundsException("Index: "+index+
", Size: "+size);
if (index < (size >> 1)) {
next = header.next;
for (nextIndex=0; nextIndex<index; nextIndex++)
next = next.next;
} else {
next = header;
for (nextIndex=size; nextIndex>index; nextIndex--)
next = next.previous;
}
}
public boolean hasNext() {
return nextIndex != size;//下一个索引号跟大小不等,返回true
}
public E next() {
checkForComodification();//版本号检查
if (nextIndex == size)//越界判断
throw new NoSuchElementException();
lastReturned = next;//上一个
next = next.next;//下一个
nextIndex++;//索引号自增
return lastReturned.element;//返回数据
}
public boolean hasPrevious() {
return nextIndex != 0;//如果索引号不等于0,说明仍有上一个元素
}
public E previous() {
//返回上一个元素的数据
if (nextIndex == 0)
throw new NoSuchElementException();
lastReturned = next = next.previous;
nextIndex--;
checkForComodification();
return lastReturned.element;
}
public int nextIndex() {
//返回迭代器当前的索引号
return nextIndex;
}
public int previousIndex() {
//返回迭代器当前的上一个索引号
return nextIndex-1;
}
public void remove() {
//移除最后一个被迭代的元素
checkForComodification();//版本检查
Entry<E> lastNext = lastReturned.next;//下一个
try {
LinkedList.this.remove(lastReturned);//移除
} catch (NoSuchElementException e) {
throw new IllegalStateException();
}
if (next==lastReturned)
next = lastNext;
else
nextIndex--;
lastReturned = header;
expectedModCount++;
}
public void set(E e) {
if (lastReturned == header)
throw new IllegalStateException();
checkForComodification();//版本号检查
lastReturned.element = e;//最后一个被迭代的元素的数据赋值
}
public void add(E e) {
checkForComodification();//版本号检查
lastReturned = header;
addBefore(e, next);//再next之前插入e
nextIndex++;索引号加1
expectedModCount++;//版本号加1
}
final void checkForComodification() {
if (modCount != expectedModCount)//当前版本号与期望版本号不等,抛异常
throw new ConcurrentModificationException();
}
}
private static class Entry<E> {
E element;//数据
Entry<E> next;//指向下一个
Entry<E> previous;//指向上一个
Entry(E element, Entry<E> next, Entry<E> previous) {//初始化
this.element = element;
this.next = next;
this.previous = previous;
}
}
private Entry<E> addBefore(E e, Entry<E> entry) {
Entry<E> newEntry = new Entry<E>(e, entry, entry.previous);//创建新元素
//新元素插入到entry之前
newEntry.previous.next = newEntry;
newEntry.next.previous = newEntry;
size++;//大小自增
modCount++;//版本号自增
return newEntry;
}
private E remove(Entry<E> e) {
//移除元素e,并返回被删除的数据
if (e == header)
throw new NoSuchElementException();
E result = e.element;
e.previous.next = e.next;
e.next.previous = e.previous;
e.next = e.previous = null;
e.element = null;
size--;
modCount++;
return result;
}
public Iterator<E> descendingIterator() {
return new DescendingIterator();
}
private class DescendingIterator implements Iterator {
//将DescendingIterator封装成与ArrayList中的Iterator操作相似
final ListItr itr = new ListItr(size());
public boolean hasNext() {
return itr.hasPrevious();
}
public E next() {
return itr.previous();
}
public void remove() {
itr.remove();
}
}
public Object clone() {
//克隆
LinkedList<E> clone = null;
try {
clone = (LinkedList<E>) super.clone();
} catch (CloneNotSupportedException e) {
throw new InternalError();
}
// Put clone into "virgin" state
clone.header = new Entry<E>(null, null, null);
clone.header.next = clone.header.previous = clone.header;
clone.size = 0;
clone.modCount = 0;
// Initialize clone with our elements
for (Entry<E> e = header.next; e != header; e = e.next)
clone.add(e.element);
return clone;
}
public Object[] toArray() {
//转成数组
Object[] result = new Object[size];
int i = 0;
for (Entry<E> e = header.next; e != header; e = e.next)
result[i++] = e.element;
return result;
}
public <T> 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 (Entry<E> e = header.next; e != header; e = e.next)
result[i++] = e.element;
if (a.length > size)
a[size] = null;
return a;
}
private static final long serialVersionUID = 876323262645176354L;//序列号
private void writeObject(java.io.ObjectOutputStream s)
throws java.io.IOException {
// Write out any hidden serialization magic
s.defaultWriteObject();
// Write out size
s.writeInt(size);//写大小
// Write out all elements in the proper order.
for (Entry e = header.next; e != header; e = e.next)
s.writeObject(e.element);//写数据
}
private void readObject(java.io.ObjectInputStream s)
throws java.io.IOException, ClassNotFoundException {
// Read in any hidden serialization magic
s.defaultReadObject();
// Read in size
int size = s.readInt();//读大小
// Initialize header
header = new Entry<E>(null, null, null);
header.next = header.previous = header;
// Read in all elements in the proper order.
for (int i=0; i<size; i++)
addBefore((E)s.readObject(), header);//度数据
}
}
Vector与ArrayList类似,只不过它是线程安全的(在写数据时都会加上同步操作)