一切尽在代码里,有错误欢迎指出
package org.utils.MyCollection;
import sun.misc.SharedSecrets;
import java.util.*;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.function.UnaryOperator;
public class MyArrayList<E> extends AbstractList<E>
implements List, RandomAccess, Cloneable, java.io.Serializable{
private static final long serialVersionUID = 8683452581122892189L;
l
/**
* 默认初始化容量
*/
private static final int DEFAULT_CAPACITY = 0;
/**
* 空对象数组
*/
private static final Object[] EMPTY_ELEMENTDATA = {};
/**
* 默认空对象数组
*/
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
/**
* ArrayList元素存储的数组缓冲取
* ArrayList的大小即这个数组缓冲区的大小,当有元素添加进,原本空的arraylist会被扩展到默认初始化容量
* transient防止这个数据域序列化
* 没有设置成private是为了简化嵌套类的操作
* 由于 ArrayList 是基于动态数组实现的,所以并不是所有的空间都被使用。因此使用了 transient 修饰,可以防止被自动序列化。
*/
transient Object[] elementData;
/**
* 集合元素个数
*/
private int size;
/**
* 数组容量初始化
* @param initialCapacity
*/
public MyArrayList(int initialCapacity){
if(initialCapacity > 0){
this.elementData = new Object[initialCapacity];
}else if(initialCapacity == 0){
this.elementData = EMPTY_ELEMENTDATA;
}else{
throw new IllegalArgumentException("非法的数组容量 : " + initialCapacity);
}
}
/**
* 空构造
*/
public MyArrayList(){
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
/**
* 使用外部集合进行构造
* @param c
*/
public MyArrayList(Collection<? extends E> c){
elementData = c.toArray();
if((size = elementData.length) != 0){
if(elementData.getClass() != Object[].class)
elementData = Arrays.copyOf(elementData, size, Object[].class);
}else{
this.elementData = EMPTY_ELEMENTDATA;
}
}
/**
* 用于精简容量
*/
public void trimToSize(){
modCount++;
if(size < elementData.length){
elementData = (size == 0)
? EMPTY_ELEMENTDATA
: Arrays.copyOf(elementData, size);
}
}
/**
* 确保最小容量 //TODO:有疑问
* @param minCapacity
*/
public void ensureCapacity(int minCapacity){
int minExpend = (elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA)
? 0
: DEFAULT_CAPACITY;
if (minCapacity > minExpend){
ensureCapacity(minCapacity);
}
}
/**
* 计算容量,如果传入的为空,则容量返回DEFAULT_CAPACITY和minCapacity之间的较大者
* @param elementData
* @param minCapacity
* @return
*/
private static int calculateCapacity(Object[] elementData, int minCapacity){
if(elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA){
return Math.max(DEFAULT_CAPACITY, minCapacity);
}
return minCapacity;
}
private void ensureCapacityInternal(int minCapacity){
ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
}
/**
* 确保明确的容量
* @param minCapacity
*/
private void ensureExplicitCapacity(int minCapacity){
modCount++;
if(minCapacity - elementData.length > 0)
grow(minCapacity);
}
/**
* array容量最大值
* 减8是因为一些VM在一个array中保留一些头,防止溢出
*/
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
/**
* 增加容量,确保至少能容纳minCapacity
* @param 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;
}
/**
* 返回list的元素个数
* @return
*/
public int size() {
return size;
}
/**
* 判断是否为空
* @return
*/
public boolean isEmpty() {
return size == 0;
}
/**
* 判断某个元素是否在list中,底层调用的是indexOf方法
* @param o
* @return
*/
public boolean contains(Object o) {
return indexOf(o) >= 0;
}
/**
* 返回list中某个元素第一次在list出现的位置,存在返回元素在list中的下标
* 不存在返回-1
* @param o
* @return
*/
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;
}
/**
* 从后往前查找元素出现的位置
* @param o
* @return
*/
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;
}
/**
* 浅拷贝
* @return
*/
public Object clone() {
try {
MyArrayList<?> v = (MyArrayList<?>) super.clone();
v.elementData = Arrays.copyOf(elementData, size);
v.modCount = 0;
return v;
} catch (CloneNotSupportedException e) {
throw new InternalError(e);
}
}
/**
* 返回list的一个Object拷贝实例,相当于创建了一个新的数组实例,元素顺序不变
* @return
*/
public Object[] toArray() {
return Arrays.copyOf(elementData, size);
}
/**
* 泛型方法
* @param a
* @param <T>
* @return
*/
@SuppressWarnings("unchecked")
public <T> T[] toArray(T[] a) {
if (a.length < size)
return (T[]) Arrays.copyOf(elementData, size, a.getClass());
System.arraycopy(elementData, 0, a, 0, size);
/**
* Object src : 原数组
* int srcPos : 从元数据的起始位置开始
* Object dest : 目标数组
* int destPos : 目标数组的开始起始位置
* int length : 要copy的数组的长度
*/
if (a.length > size)
a[size] = null;
return a;
}
/**
* 索引查值
* @param index
* @return
*/
@SuppressWarnings("unchecked")
E elementData(int index) {
return (E) elementData[index];
}
/**
* 查找某个元素
* @param index
* @return
*/
public E get(int index) {
rangeCheck(index);
return elementData(index);
}
/**
* 修改某个索引的元素为新元素
* @param index
* @param element
* @return 返回旧元素
*/
public E set(int index, E element) {
rangeCheck(index);
E oldValue = elementData(index);
elementData[index] = element;
return oldValue;
}
/**
* 增加新元素到list结尾
* @param e
* @return
*/
public boolean add(E e) {
ensureCapacityInternal(size + 1);
elementData[size++] = e;
return true;
}
/**
* 在list某个位置插入元素
* @param index
* @param element
*/
public void add(int index, E element) {
rangeCheckForAdd(index);
ensureCapacityInternal(size + 1);
System.arraycopy(elementData, index, elementData, index + 1, size - index);
elementData[index] = element;
size++;
}
/**
* 删除指定位置的元素,返回删除的元素
* @param index
* @return
*/
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;
}
/**
* 删除list中的所有给定的元素o
* @param o
* @return
*/
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;
}
/**
* 私有方法,不进行边界检查,不返回值,仅删除
* @param index
*/
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;
}
/**
* 清空list, 将所有元素置为null, 垃圾回收器会回收
*/
public void clear() {
modCount++;
for (int i = 0; i < size; i++) {
elementData[i] = null;
}
size = 0;
}
/**
* 将给集合的所有元素添加到list末尾
* @param c
* @return
*/
public boolean addAll(Collection<? extends > c) {
Object[] a = c.toArray();
int numNew = a.length;
ensureCapacityInternal(size + numNew);
System.arraycopy(a, 0, elementData, size, numNew);
size += numNew;
return numNew != 0;
}
/**
* 将给定集合中的元素添加到从list的index位置开始到给定集合长度结束
* 如原来list[1,2,3,4]
* 给定index=2,c=[11,22]
* 则返回[1,2,11,22,3,4]
* @param index
* @param c
* @return
*/
public boolean addAll(int index, Collection<? extends E> c) {
rangeCheckAdd(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;
}
/**
* 删除指定区间的元素
* @param fromIndex
* @param toIndex
*/
protected void removeRange(int fromIndex, int toIndex) {
modCount++;
int numMoved = size - toIndex;
System.arraycopy(elementData, toIndex, elementData, fromIndex, numMoved);
int newSize = size - (toIndex - fromIndex);
for (int i = newSize; i < size; i++)
elementData[i] = null;
size = newSize;
}
/**
* 范围检查
* @param index
*/
private void rangeCheck(int index) {
if (index >= size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
/**
* 增加元素时范围检查
* @param index
*/
private void rangeCheckForAdd(int index) {
if (index > size || index < 0)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
/**
* 越界异常错误消息
* @param index
* @return
*/
private String outOfBoundsMsg(int index) {
return "Index: " +index+ ", Size: "+size;
}
/**
* 从list中删除含有指定集合中元素的元素
* @param c
* @return
*/
public boolean removeAll(Collection<?> c) {
Objects.requireNonNull(c);
return batchRemove(c, false);
}
/**
* 从list中删除指定集合以外的元素,保留剩余元素
* @param c
* @return
*/
public boolean retainAll(Collection<?> c) {
Objects.requireNonNull(c);
return batchRemove(c, true);
}
/**
* 批量删除
* @param c
* @param complement(是否是补集) 如果为false,移除list中 c集合中的元素
* 如果为true,移除list中除了c集合中的所有元素
* @return 是否删除成功
*/
private boolean batchRemove(Collection<?> c, boolean complement) {
final Object[] elementData = this.elementData;
int r = 0, w = 0;
boolean modified = false;
try {
for (; r < size; r++)
if (c.contains(elementData[r]) == complement) {
elementData[w++] = elementData[r];
}
} finally {
if (r != size) {
System.arraycopy(elementData, r,
elementData, w,
size - r);
w += size - r;
}
if (w != size) {
for (int i = w; i < size; i++)
elementData[i] = null;
modCount += size - w;
size = w;
modified = true;
}
}
return modified;
}
/**
* 保存list实例的状态到流中
* @param s
* @throws java.io.IOException
*/
private void writeObject(java.io.objectOutputStream s)
throws java.io.IOException{
int expectedModCount = modCount;
s.defaultWriteObject();
s.writeInt(size);
for(int i=0; i<size; i++) {
s.writeObject(elementData[i]);
}
if(modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
}
/**
* 从反序列化中重构ArrayList实例
* @param s
* @throws java.io.IOException
* @throws ClassNotFoundException
*/
private void readObject(java.io.ObjectInputStream s)
throws java.io.IOException, ClassNotFoundException{
elementData = EMPTY_ELEMENTDATA;
s.defaultReadObject();
s.readInt();
if(size > 0) {
int capacity = calculateCapacity(elementData, size);
SharedSecrets.getJavaIOAccess().checkArray(s, Object[].class, capacity);
ensureCapacityInternal(size);
Object[] a = elementData;
for (int i=0; i<size; i++)
a[i] = s.readObject();
}
}
/**
* 返回一个从index开始的list迭代器
* @param index
* @return
*/
public ListIterator<E> listIterator(int index) {
if (index < 0 || index > size)
throw new IndexOutOfBoundsException("Index: "+index);
return new ListItr(index);
}
/**
* 返回一个list迭代器
* @return
*/
public ListIterator<E> listIterator() {
return new ListItr(0);
}
/**
* 返回一个iterator
* @return
*/
public Iterator<E> iterator() {
return new Itr();
}
/**
* Itr是AbstractList.Itr的优化版本
* 为什么会报ConcurrentModificationException异常?
* 1. Iterator 是工作在一个独立的线程中,并且拥有一个 mutex(互斥) 锁。
* 2. Iterator 被创建之后会建立一个指向原来对象的单链索引表,当原来的对象数量发生变化时,
* 这个索引表的内容不会同步改变,所以当索引指针往后移动的时候就找不到要迭代的对象,
* 3. 所以按照 fail-fast(快速失败,一种Java集合的错误检测机制) 原则 Iterator 会马上抛出 java.util.ConcurrentModificationException 异常。
* 4. 所以 Iterator 在工作的时候是不允许被迭代的对象被改变的。
* 但你可以使用 Iterator 本身的方法 remove() 来删除对象,
* 5. Iterator.remove() 方法会在删除当前迭代对象的同时维护索引的一致性。
*/
private class Itr implements Iterator<E> {
int cursor;
int lastRet = -1;
int expectedModCount = modCount;
Itr() {}
/**
* 是否有下一个元素
* @return
*/
public boolean hasNext() {
return cursor != size;
}
@SuppressWarnings("unchecked")
public E next() {
rangeForComodification();
int i = cursor;
if (i >= size)
throw new NoSuchElementException();
Object[] elementData = MyArrayList.this.elementData;
if (i >= elementData.length)
throw new ConcurrentModificationException();
cursor = i + 1;
return (E) elementData[lastRet = i];
}
public void remove() {
if (lastRet < 0)
throw new IllegalStateException();
checkForComodification();
try {
MyArrayList.this.remove(lastRet);
cursor = lastRet;
lastRet = -1;
expectedModCount = modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
/**
* jdk 1.8中使用的方法
* 将list中的所有元素都给了consumer,可以使用这个方法来取出元素
* @param consumer
*/
@Override
@SuppressWarnings("unchecked")
public void forEachRemaining(Consumer<? super E> consumer) {
Objects.requireNonNull(consumer);
final int size = MyArrayList.this.size;
int i = cursor;
if (i >= size) {
return;
}
final Object[] elementData = MyArrayList.this.elementData;
if (i >= elementData.length) {
throw new ConcurrentModificationException();
}
while (i != size && modCount == expectedModCount) {
consumer.accept((E) elementData[i++]);
}
cursor = i;
lastRet = i - 1;
checkForComodification();
}
/**
* 检查modCount是否等于expectedModCount
* 在迭代时list集合的元素数量发生变化时会造成这两个值不相等
* 所以 Iterator 在工作的时候是不允许被迭代的对象被改变的
* 不然会报异常
*/
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}
/**
* AbstractList.ListItr 的优化版本
* ListIterator 与普通的 Iterator 的区别:
* - 它可以进行双向移动,而普通的迭代器只能单向移动
* - 它可以添加元素(有 add() 方法),而后者不行
*/
private class ListItr extends Itr implements ListIterator<E> {
ListItr(int index) {
super();
cursor = index;
}
/**
* 是否有前一个元素
* @return
*/
public boolean hasPrevious() {
return cursor != 0;
}
/**
* 获取下一个元素的索引
* @return
*/
public int nextIndex() {
return cursor;
}
/**
* 获取cursor前一个元素的索引,注意cursor是一个元素返回的索引!!!
* - 是 cursor 前一个,而不是当前元素前一个的索引。
* - 若调用 next() 后马上调用该方法,则返回的是当前元素的索引。
* - 若调用 next() 后想获取当前元素前一个元素的索引,需要连续调用两次该方法。
* @return
*/
public int previousIndex() {
return cursor - 1;
}
/**
* 返回前一个元素
* @return
*/
@SuppressWarnings("unchecked")
public E previous() {
checkForComodification();
int i = cursor - 1;
if (i < 0)
throw new NoSuchElementException();
Object[] elementData = MyArrayList.this.elementData;
if (i >= elementData.length)
throw new ConcurrentModificationException();
cursor = i;
return (E)elementData[lastRet = i];
}
/**
* 将数组的最后一个元素,设置成元素e
* @param e
*/
public void set(E e) {
if (lastRet < 0)
throw new IllegalStateException();
checkForComodification();
try {
MyArrayList.this.set(lastRet, e);
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
/**
* 添加元素
* @param e
*/
public void add(E e) {
checkForComodification();
try {
int i = cursor;
MyArrayList.this.add(i, e);
cursor = i + 1;
lastRet = -1;
expectedModCount = modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
}
/**
* 获取从 fromIndex 到 toIndex 之间的子集合(左闭右开区间)
* - 若 fromIndex == toIndex,则返回的空集合
* - 对该子集合的操作,会影响原有集合
* - 当调用了 subList() 后,若对原有集合进行删除操作(删除subList 中的首个元素)时,
* 会抛出异常 java.util.ConcurrentModificationException
* 这个和Itr的原因差不多由于modCount发生了改变,对集合的操作需要用子集合提供的方法
* - 该子集合支持所有的集合操作
* 原因看 SubList 内部类的构造函数就可以知道
* @param fromIndex
* @param toIndex
* @return
*/
public List<E> subList(int fromIndex, int toIndex) {
subListRangeCheck(fromIndex, toIndex, size);
return new SubList(this, 0, fromIndex, toIndex);
}
/**
* 检查索引的合法性
* @param fromIndex
* @param toIndex
* @param size
*/
static void subListRangeCheck(int fromIndex, int toIndex, int size) {
if (fromIndex < 0)
throw new IndexOutOfBoundsException("fromIndex = " + fromIndex);
if (toIndex > size)
throw new IndexOutOfBoundsException("toIndex = " + toIndex);
if (fromIndex > toIndex)
throw new IndexOutOfBoundsException("fromIndex(" + fromIndex +
") > toIndex" + toIndex);
}
/**
* 私有类
* 嵌套内部类:也实现了 RandomAccess,提供快速随机访问特性
* 这个是通过映射来实现的
*/
private class SubList extends AbstractList<E> implements RandomAccess {
private final AbstractList<E> parent;
private final int parentOffset;
private final int offset;
int size;
/**
* 看到这部分,就理解为什么对 SubList 的操作,会影响父集合--->
* 因为子集合的处理,仅仅是给出了一个映射到父集合相应区间的引用
* 再加上 final,的修饰,就能明白为什么进行了截取子集合操作后,
* 父集合不能删除 SubList 中的首个元素了--->offset 不能更改
* @param parent
* @param offset
* @param fromIndex
* @param toIndex
*/
SubList(AbstractList<E> parent, int offset,
int fromIndex, int toIndex) {
this.parent = parent;
this.parentOffset = offset;
this.offset = offset + fromIndex;
this.size = toIndex - fromIndex;
this.modCount = MyArrayList.this.modCount;
}
/**
* 修改某索引处为新值,返回旧值
* @param index
* @param e
* @return
*/
public E set(int index, E e) {
rangeCheck(index);
checkForComodification();
E oldValue = MyArrayList.this.elementData(offset + index);
MyArrayList.this.elementData[offset + index] = e;
return oldValue;
}
/**
* 获取指定索引处的值
* @param index
* @return
*/
public E get(int index) {
rangeCheck(index);
checkForComodification();
return MyArrayList.this.elementData(offset + index);
}
/**
* 返回元素的数量
* @return
*/
public int size() {
checkForComodification();
return this.size;
}
/**
* 指定位置添加元素
* @param index
* @param e
*/
public void add(int index, E e) {
rangeCheck(index);
checkForComodification();
parent.add(parentOffset + index, e);
this.modCount = parent.modCount;
this.size++;
}
/**
* 删除指定索引处的值
* @param index
* @return
*/
public E remove(int index) {
rangeCheck(index);
checkForComodification();
E result = parent.remove(parentOffset + index);
this.modCount = parent.modCount;
this.size--;
return result;
}
/**
* 移除subList中的[fromIndex,toIndex)之间的元素
* @param fromIndex
* @param toIndex
*/
protected void removeRange(int fromIndex, int toIndex) {
checkForModification();
parent.removeRange(parentOffset + fromIndex,
parentOffset + toIndex);
this.modCount = parent.modCount;
this.size -= toIndex - fromIndex;
}
/**
* 在subList末尾添加给定集合中的所有元素
* @param c
* @return
*/
public boolean addAll(Collection<? extends E> c) {
return addAll(this.size, c);
}
/**
* 添加给定集合所有元素到指定index
* @param index
* @param c
* @return
*/
public boolean addAll(int index, Collection<? extends E> c) {
rangeCheckForAdd(index);
int cSize = c.size();
if (cSize == 0)
return false;
checkForComodification();
parent.addAll(parentOffset + index, c);
this.modCount = parent.modCount;
this.size += cSize;
return true;
}
/**
* subList中的迭代器
* @return
*/
public Iterator<E> iterator() {
return listIterator();
}
/**
* 返回从指定索引开始到结束的带有元素的list迭代器
* @param index
* @return
*/
public ListIterator<E> listIterator(final int index) {
checkForComodification();
rangeCheckForAdd(index);
final int offset = this.offset;
return new ListIterator<E>() {
int cursor = index;
int lastRet = -1;
int expectedModCount = MyArrayList.this.modCount;
public boolean hasNext() {
return cursor != SubList.this.size;
}
@SuppressWarnings("unchecked")
public E next() {
checkForComodification();
int i = cursor;
if (i > SubList.this.size)
throw new NoSuchElementException();
Object[] element = MyArrayList.this.elementData;
if (offset + i >= elementData.length)
throw new ConcurrentModificationException();
cursor = i + 1;
return (E) elementData[offset + (lastRet = i)];
}
public boolean hasPrevious() {
return cursor != 0;
}
@SuppressWarnings("unchecked")
public E previous() {
checkForComodification();
int i = cursor - 1;
if (i < 0)
throw new NoSuchElementException();
Object[] elementData = MyArrayList.this.elementData;
if (offset + 1 >= elementData.length)
throw new ConcurrentModificationException();
cursor = i;
return (E) elementData[offset + (last = i)];
}
@SuppressWarnings("unchecked")
public void forEachRemaining(Consumer<? super E> consumer) {
Objects.requireNonNull(consumer);
final int size = SubList.this.size;
int i = cursor;
if (i >= size) {
return;
}
final Object[] elementData = ArrayList.this.elementData;
if (offset + i >= elementData.length) {
throw new ConcurrentModificationException();
}
while (i != size && modCount == expectedModCount) {
consumer.accept((E) elementData[offset + (i++)]);
}
lastRet = cursor = i;
checkForComodification();
}
public int nextIndex() {
return cursor;
}
public int previousIndex() {
return cursor - 1;
}
public void remove() {
if (lastRet < 0)
throw new IllegalStateException();
checkForComodification();
try {
SubList.this.remove(lastRet);
cursor = lastRet;
lastRet = -1;
expectedModCount = MyArrayList.this.modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
public void set(E e) {
if (lastRet < 0)
throw new IllegalStateException();
checkForComodification();
try {
MyArrayList.this.set(offset + lastRet, e);
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
public void add(E e) {
checkForComodification();
try {
int i = cursor;
SubList.this.add(i, e);
cursor = i + 1;
lastRet = -1;
expectedModCount = MyArrayList.this.modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
final void checkForComodification() {
if (expectedModCount != MyArrayList.this.modCount)
throw new ConcurrentModificationException();
}
};
}
public List<E> subList(int fromIndex, int toIndex) {
subListRangeCheck(fromIndex, toIndex, size);
return new SubList(this, offset, fromIndex, toIndex);
}
private void rangeCheck(int index) {
if (index < 0 || index >= this.size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
private void rangeCheckForAdd(int index) {
if (index < 0 || index > this.size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
private String outOfBoundsMsg(int index) {
return "Index: " +index+", size: " + this.size;
}
private void checkForComodification() {
if (MyArrayList.this.modCount != this.modCount)
throw new ConcurrentModificationException();
}
/**
* subList方法:获取一个分割器
* - fail-fast
* - late-binding:后期绑定
* - java8 开始提供
*/
public Spliterator<E> spliterator() {
checkForComodification();
return new ArrayListSpliterator<E>(MyArrayList.this, offset,
offset + this.size, this.modCount);
}
}
@Override
public void forEach(Consumer<? super E> action) {
Objects.requireNonNull(action);
final int expectedModCount = modCount;
@SuppressWarnings("unchecked")
final E[] elementData = (E[]) this.elementData;
final int size = this.size;
for (int i=0; modCount==expectedModCount && i < size; i++) {
action.accept(elementData[i]);
}
if (modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
}
/**
* 获取一个分割器
* - fail-fast 机制和itr,subList一个机制
* - late-binding:后期绑定
* - java8 开始提供
* @return a {@code Spliterator} over the elements in this list
* @since 1.8
*/
@Override
public Spliterator<E> spliterator() {
return new ArrayListSpliterator<>(this, 0, -1, 0);
}
/**
* 基于索引的、二分的、懒加载的分割器
* @param <E>
*/
static final class ArrayListSpliterator<E> implements Spliterator<E> {
private final MyArrayList<E> list;
private int index;
private int fence;
private int expentedModCount;
ArrayListSpliterator(MyArrayList<E> list, int origin, int fence, int expentedModCount) {
this.list = list;
this.index= origin;
this.fence = fence;
this.expentedModCount = expentedModCount;
}
private int getFence() {
int hi;
MyArrayList<E> lst;
if ((hi = fence) < 0){
if ((lst = list) == null)
hi = fence = 0;
else {
expentedModCount = lst.modCount;
hi = fence = lst.size;
}
}
return hi;
}
/**
* 分割list,返回一个新分割出的spliterator实例
* 相当于二分法,这个方法会递归
* 1.ArrayListSpliterator本质上还是对原list进行操作,只是通过index和fence来控制每次处理范围
* 2.也可以得出,ArrayListSpliterator在遍历元素时,不能对list进行结构变更操作,否则抛错。
* @return
*/
public ArrayListSpliterator<E> trySplit() {
int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
/**如: | 0 | 1 | 2 | 3 | 4 | 5 | 数组长度为6 的进行 split
* 结束角标 hi:6 开始角标lo:0 mid:3 lo<mid
* [0,3) 同时 lo:3 hi:6 mid:4
* [3,4) 同时 lo:4 hi:6 mid:5
* [4,5) 同时 lo:5 hid:6 mid:5
* null
*/
return (lo >= mid)
? null
: new ArrayListSpliterator<>(list, lo, index=mid, expentedModCount);
}
public boolean tryAdvance(Consumer<? super E> action) {
if (action == null)
throw new NullPointerException();
int hi = getFence(), i = index;
if (i < hi) {
index = i + 1;
@SuppressWarnings("unchecked") E e = (E)list.elementData[i];
action.accept(e);
if (list.modCount != expentedModCount)
throw new ConcurrentModificationException();
return true;
}
return false;
}
/**
* 顺序遍历处理所有剩下的元素
* Consumer类型,传入值处理
* @param action
*/
public void forEachRemaining(Consumer<? super E> action) {
int i, hi, mc;
MyArrayList<E> lst; Object[] a;
if (action == null)
throw new NullPointerException();
if ((lst = list) != null && (a = lst.elementData) != null) {
if ((hi = fence) < 0) {
mc = lst.modCount;
hi = lst.size;
}
else
mc = expentedModCount;
if ((i = index) >= 0 && (index =hi) <= a.length) {
for (; i < hi; ++i){
@SuppressWarnings("unchecked") E e = (E) a[i];
action.accept(e);
}
if (lst.modCount == mc)
return ;
}
}
throw new ConcurrentModificationException();
}
/**
* 估算大小
* @return
*/
public long estimateSize() {
return (long) (getFence() - index);
}
/**
* 打上特征值:可以返回size
* @return
*/
public int characteristics() {
return Spliterator.ORDERED | Spliterator.SIZED | Spliterator.SUBSIZED;
}
}
/**
* 根据Predicate条件来移除元素
* 将所有元素依次根据filter的条件判断
* Predicate 是 传入元素 返回 boolean 类型的接口
* @param filter
* @return
*/
@Override
public boolean removeIf(Predicate<? super E> filter) {
Objects.requireNonNull(filter);
int removeCount = 0;
final BitSet removeSet = new BitSet(size);
final int expectedModCount = modCount;
final int size = this.size;
for (int i=0; modCount == expectedModCount && i < size; i++) {
@SuppressWarnings("unchecked")
final E element = (E) elementData[i];
if (filter.test(element)){
removeSet.set(i);
removeCount++;
}
}
if (modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
final boolean anyToRemove = removeCount > 0;
if (anyToRemove) {
final int newSize = size - removeCount;
for (int i=0, j=0; (i<size) && (j < newSize); i++, j++) {
i = removeSet.nextClearBit(i);
elementData[j] = elementData[i];
}
for(int k=newSize; k < size; k++) {
elementData[k] = null;
}
this.size = newSize;
if (modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
modCount++;
}
return anyToRemove;
}
/**
* UnaryOperator 接受一个什么类型的参数,返回一个什么类型的参数
* 对数组中的每一个元素进行一系列的操作,返回同样的元素,
* 如果 List<Student> lists 将list集合中的每一个student姓名改为张三
* 使用这个方法就非常方便
* @param operator
*/
@Override
@SuppressWarnings("unchecked")
public void replaceAll(UnaryOperator<E> operator) {
Objects.requireNonNull(operator);
final int expectedModCount = modCount;
final int size = this.size;
for (int i=0; modCount == expectedModCount && i < size; i++) {
elementData[i] = operator.apply((E) elementData[i]);
}
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
modCount++;
}
/**
* 根据 Comparator条件进行排序
* @param c
*/
@Override
@SuppressWarnings("unchecked")
public void sort(Comparator<? super E> c) {
final int expectedModCount = modCount;
Arrays.sort((E[])elementData, 0, size, c);
if (modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
modCount++;
}
}