JDK源码分析——Iterator接口、Collection接口、ArrayList类
##集合框架
从类图结构可以了解 java.util包下的2个大类:
1、Collecton:可以理解为主要存放的是单个对象
2、Map:可以理解为主要存储key-value类型的对象
##Iterator接口分析
package java.lang;
import java.util.Iterator;
import java.util.Objects;
import java.util.Spliterator;
import java.util.Spliterators;
import java.util.function.Consumer;
/**
* 实现这个接口允许一个对象作为“for-each循环”语句的目标
* @param <T> the type of elements returned by the iterator
*
* @since 1.5
* @jls 14.14.2 The enhanced for statement
*/
public interface Iterable<T> {
/**
* 返回类型元素的迭代器
*/
Iterator<T> iterator();
/**
*为对象的每个元素执行给定的操作,直到处理完所有元素或操作抛出异常为止。
*除非实现类另有指定,否则操作将按照迭代顺序执行(如果指定了迭代顺序)。由操作引发的异常被转发给调用方。
* @since 1.8
*/
default void forEach(Consumer<? super T> action) {
Objects.requireNonNull(action);
for (T t : this) {
action.accept(t);
}
}
/**
*Spliterator 字面意思可分割的迭代器,不同以往的iterator需要顺序迭代,Spliterator可以分割为若干个小的迭代器进行并行操作,既可以实现多线程操作提高效率,又可以避免普通迭代器的fail-fast机制所带来的异常。Spliterator可以配合1.8新加的Stream进行并行流的实现,大大提高处理效率。!
* @since 1.8
*/
default Spliterator<T> spliterator() {
return Spliterators.spliteratorUnknownSize(iterator(), 0);
}
}
##Collection接口分析
package java.util;
import java.util.function.Predicate;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
*
* @author Josh Bloch
* @author Neal Gafter
*/
public interface Collection<E> extends Iterable<E> {
// Query Operations
//返回此集合的大小 小于等于Integer的最大值
int size();
//判断此集合不包含任何元素
boolean isEmpty();
//判断此集合是否包含此对象
boolean contains(Object o);
//遍历集合中的元素
Iterator<E> iterator();
//返回此集合中包含的所有元素数组
Object[] toArray();
//返回此集合中包含所有元素的数组; 返回的数组的运行时类型是指定数组的运行时类型。
<T> T[] toArray(T[] a);
//确保此集合包含指定的元素(可选操作)此处不一定是增加 只是确保此元素存在。
boolean add(E e);
//从该集合中删除指定元素的单个实例(如果存在)(可选操作)。
boolean remove(Object o);
//如果此集合包含指定 集合中的所有元素,则返回true。
boolean containsAll(Collection<?> c);
//确保集合中的所有元素添加到此集合(可选操作) 。
boolean addAll(Collection<? extends E> c);
//删除指定集合中包含的所有此集合的元素(可选操作)。
boolean removeAll(Collection<?> c);
//删除该集合中满足给定谓词的所有元素。在迭代期间或由谓词引发的错误或运行时异常被转发给调用者。
//如果无法从该集合中移除元素,则将不支持操作异常。如果不能删除匹配元素,或者一般不支持移除,则实现可能引发此异常UnsupportedOperationException。
default boolean removeIf(Predicate<? super E> filter) {
Objects.requireNonNull(filter);
boolean removed = false;
final Iterator<E> each = iterator();
while (each.hasNext()) {
if (filter.test(each.next())) {
each.remove();
removed = true;
}
}
return removed;
}
//仅保留此集合中包含在指定集合中的元素(可选操作)。
boolean retainAll(Collection<?> c);
//从此集合中删除所有元素(可选操作)。
void clear();
//将指定的对象与此集合进行比较以获得相等性。
boolean equals(Object o);
//返回此集合的哈希码值。
int hashCode();
//创建一个Spliterator在这个集合中的元素 ***JDK8新特性 之后深入了解!
@Override
default Spliterator<E> spliterator() {
return Spliterators.spliterator(this, 0);
}
//返回以此集合作为源的顺序 Stream 。
default Stream<E> stream() {
return StreamSupport.stream(spliterator(), false);
}
default Stream<E> parallelStream() {
return StreamSupport.stream(spliterator(), true);
}
}
Spliterator是JDK1.8新特性
Spliterator是一个可分割迭代器(splitable iterator),可以并行遍历元素,对于并行处理的能力大大增强。
#常见的集合类分析
##List (ArrayList、 LinkedList、 Vector、 Stack)
ArrayList源码如下:
package java.util;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.function.UnaryOperator;
import sun.misc.SharedSecrets;
/*
* Java Collections Framework Java集合框架
* 数组队列 相当于动态数组
*
* @author Josh Bloch
* @author Neal Gafter
* @see Collection
* @see List
* @see LinkedList
* @see Vector
* @since 1.2
*/
public class ArrayList<E> extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{
private static final long serialVersionUID = 8683452581122892189L;
/**
* Default initial capacity.
* 默认初始容量 10
*/
private static final int DEFAULT_CAPACITY = 10;
/**
* Shared empty array instance used for empty instances.
* 用于空实例的共享空数组实例 {}
*/
private static final Object[] EMPTY_ELEMENTDATA = {};
/**
Shared empty array instance used for default sized empty instances. We
distinguish this from EMPTY_ELEMENTDATA to know how much to inflate when
first element is added.
用于默认大小的空实例的共享空数组实例。我们将其与EMPTY_ELEMENTDATA区分开来,
以了解第一个元素被添加时候需要膨胀多少
*/
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
/**
The array buffer into which the elements of the ArrayList are stored.
The capacity of the ArrayList is the length of this array buffer. Any
empty ArrayList with elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA
will be expanded to DEFAULT_CAPACITY when the first element is added.
存储ArrayList元素的数组缓冲区。
ArrayList的容量就是这个数组缓冲区的长度。任何
空ArrayList与elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA
将在添加第一个元素时扩展到DEFAULT_CAPACITY。
transient 为了不被序列化,节省空间,
transient Object[] elementData; // non-private to simplify nested class access
/**
* 此数组的大小
*
* @serial
*/
private int size;
/**
*构造具有指定初始容量的空列表。
* 逻辑: 如果指定初始容量大于0 new Object[]的数组 存储到 此elementData中
* 如果为0 空对象数组存储到此数组中
* 小于0 报IllegalArgumentException
*/
public ArrayList(int initialCapacity) {
if (initialCapacity > 0) {
this.elementData = new Object[initialCapacity];
} else if (initialCapacity == 0) {
this.elementData = EMPTY_ELEMENTDATA;
} else {
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
}
}
/**
* 构造具有默认10初始容量的空列表。
* 默认大小的空实例的共享空数组实例 赋值此数组
*/
public ArrayList() {
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
/**
构造包含指定元素的列表集合返回的顺序迭代器。
逻辑:1.将指定集合的所有元素数组 赋值给此ArrayList
2.如果此数组的长度不为0, ,需要在if (elementData.getClass() != Object[].class)进行判断。
Arrays.asList()返回的是Arrays$ArrayList 造函数的集合是Arrays$ArrayList,那么它返回的数组类型不一定是Object[]
如果此数组长度为0 空数组赋值给此数组
*/
public ArrayList(Collection<? extends E> c) {
elementData = c.toArray();
if ((size = elementData.length) != 0) {
// c.toArray might (incorrectly) not return Object[] (see 6260652)
if (elementData.getClass() != Object[].class)
elementData = Arrays.copyOf(elementData, size, Object[].class);
} else {
// replace with empty array.
this.elementData = EMPTY_ELEMENTDATA;
}
}
/**
此方法将elementData的数组设置为ArrayList实际的容量,动态增长的多余容量被删除了。
比如先将一个数组先添加10个元素,容量还是10,size=10,如果加1个元素,容量变成15,size=11,
用Arrays.copyOf()方法,将容量缩微11. 根据size去copy。
*/
public void trimToSize() {
modCount++;
if (size < elementData.length) {
elementData = (size == 0)
? EMPTY_ELEMENTDATA
: Arrays.copyOf(elementData, size);
}
}
/**
增加这个ArrayList实例的容量,如果必要的,以确保它至少可以容纳元素的数量
由最小容量参数指定。
* 逻辑: 1.如果此数组不是默认指定10大小的空数组,最小容量为0,不然为10
* 如果给的指定容量的大小 大于此数组的容量(0,或者10),去执行ensureExplicitCapacity(min)确保最小容量。
* 如果给的是11大于10,
*
* @param minCapacity the desired minimum capacity
*/
public void ensureCapacity(int minCapacity) {
int minExpand = (elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA)
// any size if not default element table
? 0
// larger than default for default empty table. It's already
// supposed to be at default size.
: DEFAULT_CAPACITY;
if (minCapacity > minExpand) {
ensureExplicitCapacity(minCapacity);
}
}
/**
静态方法 计算容量 calculateCapacit(x数组元素,y最小容量)
如果此x数组为默认的10容量的空数组,返回10和y的最大值。 不然返回y。
*/
private static int calculateCapacity(Object[] elementData, int minCapacity) {
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
return Math.max(DEFAULT_CAPACITY, minCapacity);
}
return minCapacity;
}
/**
确保内部容量
逻辑: 1.如果此数组不是默认的10容量的空数组,返回10或者给定的最小容量的最大值
2.如果不是默认的10容量的空数组,返回给定的最小容量
3.经过1、2 给出确保容量的最小值 ,与数组size大小去判断是否需要扩容。
*/
private void ensureCapacityInternal(int minCapacity) {
ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
}
/**
确保当前最小容量可以正常使用
如果当前最小容量为5,但此数组长度为6,就需要扩容 grow(5)
如果最小容量 > 此数组长度 不需要任何操作
*/
private void ensureExplicitCapacity(int minCapacity) {
modCount++;
// overflow-conscious code
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
/**
The maximum size of array to allocate.
Some VMs reserve some header words in an array.
Attempts to allocate larger arrays may result in
OutOfMemoryError: Requested array size exceeds VM limit
虚拟机允许的最大的数组大小为 Integer最大值减8(一些虚拟机在数组中保留一些标题词)2^31-1-8 = 2147483639
*/
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
/**
Increases the capacity to ensure that it can hold at least the
number of elements specified by the minimum capacity argument.
增加容量,以确保它至少可以容纳由最小容量参数指定的元素数。
1.数组的长度赋值给old容量
2.old容量 + old容量 右移一位(101 变 10 5变2) 大概为1.5倍的old容量 赋值给new容量
3.如果new容量 小于给定的最小容量值,new容量赋值为给定的最小容量
4.如果new容量 大于Integer.MAX_VALUE - 8 ,则调用hugeCapacity(最小容量)方法
如果最小容量小于0 OutOfMemoryError ,如果最小容量大于Integer.MAX_VALUE - 8,返回 Integer.MAX_VALUE
5.不然 就返回new容量的大小的elementData的拷贝
*
* @param minCapacity the desired minimum capacity
*/
private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
int newCapacity = oldCapacity + (oldCapacity >> 1);
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
if (newCapacity - MAX_ARRAY_SIZE > 0)
newCapacity = hugeCapacity(minCapacity);
// minCapacity is usually close to size, so this is a win:
elementData = Arrays.copyOf(elementData, newCapacity);
}
private static int hugeCapacity(int minCapacity) {
if (minCapacity < 0) // overflow
throw new OutOfMemoryError();
return (minCapacity > MAX_ARRAY_SIZE) ?
Integer.MAX_VALUE :
MAX_ARRAY_SIZE;
}
/**
返回此数组的大小
*/
public int size() {
return size;
}
/**
判断此数组大小是否为0
*/
public boolean isEmpty() {
return size == 0;
}
/**
判断此数组是否包含此对象
*/
public boolean contains(Object o) {
return indexOf(o) >= 0;
}
/**
判断此数组包含指定对象第一个下标
1.如果指定对象为null,从小到大循环遍历此数组中的元素中第一个为null的下标
2.如果指定对象不为null,从小到大循环遍历此数组中的元素中第一个为此对象(此处用equals方法判断)的下标
3.如果找不到返回-1
*/
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;
}
/**
判断此数组包含指定对象最后一个下标
1.如果指定对象为null,从大到小循环遍历此数组中的元素中第一个为null的下标
2.如果指定对象不为null,从大到小循环遍历此数组中的元素中第一个为此对象(此处用equals方法判断)的下标
3.如果找不到返回-1
*/
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;
}
/**
数组的克隆
1.调用超类的克隆方法
2.Arrays拷贝此数组,指定数组大小的长度
3.将数组的修改次数赋值为0
4.返回此拷贝数组
*/
public Object clone() {
try {
ArrayList<?> v = (ArrayList<?>) super.clone();
v.elementData = Arrays.copyOf(elementData, size);
v.modCount = 0;
return v;
} catch (CloneNotSupportedException e) {
// this shouldn't happen, since we are Cloneable
throw new InternalError(e);
}
}
/**
返回此数组的对象数组 Arrays.copyOf拷贝方法。
*/
public Object[] toArray() {
return Arrays.copyOf(elementData, size);
}
/**
*
*/
@SuppressWarnings("unchecked")
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());
//将指定源数组中的数组从指定位置复制到目标数组的指定位置。
//src - 源数组。 srcPos - 源数组中的起始位置。dest - 目标数组。 destPos - 目的地数据中的起始位置。
length - 要复制的数组元素的数量。
//System.arraycopy(Object src, int srcPos, Object dest, int destPos, int length)
System.arraycopy(elementData, 0, a, 0, size);
if (a.length > size)
a[size] = null;
return a;
}
// Positional Access Operations
/**
此方法 为default 只在当前包下可以使用
查找索引位置上的元素返回值 类型不固定
*/
@SuppressWarnings("unchecked")
E elementData(int index) {
return (E) elementData[index];
}
/**
* Returns the element at the specified position in this list.
*
* @param index index of the element to return
* @return the element at the specified position in this list
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
//查找索引位置上的元素返回值 类型不固定 但会先查询是否会超出范围
public E get(int index) {
rangeCheck(index);
return elementData(index);
}
/**
在索引index位置上 设置新的元素 并返回旧的元素
1.判断索引位置是否 <0 || >= size 抛异常
2.在索引index位置上 设置新的元素
3.返回旧的元素
*/
public E set(int index, E element) {
rangeCheck(index);
E oldValue = elementData(index);
elementData[index] = element;
return oldValue;
}
/**
* 新增元素
* 逻辑:
*
* 1.确保容量正确
* 2.最后一个元素设置为指定元素
* 3.返回true
*/
public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
/**
在指定索引位置上新增元素
逻辑: 1.判断索引位置是否 <0 || >= size 抛异常
2.确保容量正确
3.拷贝数组元素 从数组索引index开始 拷贝数组第index+1项到最后一项,
4.将索引位置index元素设置成指定的元素
5.size++
*/
public void add(int index, E element) {
rangeCheckForAdd(index);
ensureCapacityInternal(size + 1); // Increments modCount!!
System.arraycopy(elementData, index, elementData, index + 1,
size - index);
elementData[index] = element;
size++;
}
/**
*删除指定索引的元素
逻辑: 1.判断索引位置是否 <0 || >= size 抛异常
2.修改次数+1
3.需要被移动元素的数量size - index - 1;
4.拷贝数组
5.返回旧数组
*/
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; // clear to let GC do its work
return oldValue;
}
/**
*删除一个指定的元素
逻辑: 1.判断指定的元素是否为null
2。若为null,循环遍历每个元素 判断是否为null,若为null,fastRemove(index)方法【和remove(index)差不多就是不用检查索引位置 和不返回值】 若有返回true
3.若不为null,循环遍历每个元素,equals方法判断是否相同,fastRemove(index)方法,如有返回true
4.如果没有此指定的元素 返回false
*/
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;
}
/*
快速删除指定索引元素的方法
和remove(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; // clear to let GC do its work
}
/**
* Removes all of the elements from this list. The list will
* be empty after this call returns.
*/
public void clear() {
modCount++;
// clear to let GC do its work
for (int i = 0; i < size; i++)
elementData[i] = null;
size = 0;
}
/**
* 将指定的集合全部添加到当前数组
* 指定集合的数组 拷贝到此数组中
/
public boolean addAll(Collection<? extends E> c) {
Object[] a = c.toArray();
int numNew = a.length;
ensureCapacityInternal(size + numNew); // Increments modCount
System.arraycopy(a, 0, elementData, size, numNew);
size += numNew;
return numNew != 0;
}
/**
* 将指定数组插到该集合中的索引index上
1.检查索引值 >0 且 < size值
2.确保容量安全size+定制数组的length
3.判断原数组要移动元素的数量
4.如果要移动的数量大于0, 比如[1,2,3,4,5] addAll (4, [6,7,8,9,10,11])
4(1) 如果要移动的数量大于0,将a数组从索引位置x后的所有元素复制成a1,复制到a数组的索引x+指定集合长度leng (x+leng)索引位置上,
移动a数组从索引位置x后的所有元素的长度
System.arraycopy(elementData, index, elementData, index + numNew, numMoved);-> [1,2,3,4,5,,,,,,5]
4(2) 将 指定集合从索引0开始到原拷贝数组的索引index上,长度为指定结合的长度
System.arraycopy(a, 0, elementData, index, numNew); -> [1,2,3,4,6,7,8,9,10,11,5]
5.此时集合的大小为原size+指定集合的长度
6.返回 指定集合长度不等于0的boolean值
*/
public boolean addAll(int index, Collection<? extends E> c) {
rangeCheckForAdd(index);
Object[] a = c.toArray();
int numNew = a.length;
ensureCapacityInternal(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;
}
/**
删除所有从索引x到索引y的所有元素 包头不包尾
逻辑:
1.涉及到修改的操作,都会有modCount++;这个操作
[1,2,3,4,5] removeRange(1,3) 4,5 1,2->4,3->5,4,5 -> 1,4,5,4->null, 5->null -> 1,4,5
2.要移动的数量 to-from
3.拷贝
*/
protected void removeRange(int fromIndex, int toIndex) {
modCount++;
int numMoved = size - toIndex;
System.arraycopy(elementData, toIndex, elementData, fromIndex,
numMoved);
// clear to let GC do its work
int newSize = size - (toIndex-fromIndex);
for (int i = newSize; i < size; i++) {
elementData[i] = null;
}
size = newSize;
}
/**
* Checks if the given index is in range. If not, throws an appropriate
* runtime exception. This method does *not* check if the index is
* negative: It is always used immediately prior to an array access,
* which throws an ArrayIndexOutOfBoundsException if index is negative.
*/
private void rangeCheck(int index) {
if (index >= size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
/**
* A version of rangeCheck used by add and addAll.
*/
private void rangeCheckForAdd(int index) {
if (index > size || index < 0)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
/**
* Constructs an IndexOutOfBoundsException detail message.
* Of the many possible refactorings of the error handling code,
* this "outlining" performs best with both server and client VMs.
* 构造IndexOutOfBoundsException索引越界详细信息。
*/
private String outOfBoundsMsg(int index) {
return "Index: "+index+", Size: "+size;
}
/**
* 移除指定的包含集合中的元素
* 逻辑:
* 1.判空 NullPointerException
* 2.执行下面batchRemove(Collection<?> c, false)方法
*/
public boolean removeAll(Collection<?> c) {
Objects.requireNonNull(c);
return batchRemove(c, false);
}
/**
* 仅保留此列表中包含在指定集合中的元素。
* 换句话说,从此列表中删除其中不包含在指定集合中的所有元素
* 1.判空 NullPointerException
* 2.执行下面batchRemove(Collection<?> c, true)方法
*/
public boolean retainAll(Collection<?> c) {
Objects.requireNonNull(c);
return batchRemove(c, true);
}
/**
* 1.
*/
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 {
// Preserve behavioral compatibility with AbstractCollection,
// even if c.contains() throws.
if (r != size) {
System.arraycopy(elementData, r,
elementData, w,
size - r);
w += size - r;
}
if (w != size) {
// clear to let GC do its work
for (int i = w; i < size; i++)
elementData[i] = null;
modCount += size - w;
size = w;
modified = true;
}
}
return modified;
}
/**
* Save the state of the <tt>ArrayList</tt> instance to a stream (that
* is, serialize it).
*
* @serialData The length of the array backing the <tt>ArrayList</tt>
* instance is emitted (int), followed by all of its elements
* (each an <tt>Object</tt>) in the proper order.
*/
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 size as capacity for behavioural compatibility with clone()
s.writeInt(size);
// 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();
}
}
/**
* Reconstitute the <tt>ArrayList</tt> instance from a stream (that is,
* deserialize it).
*/
private void readObject(java.io.ObjectInputStream s)
throws java.io.IOException, ClassNotFoundException {
elementData = EMPTY_ELEMENTDATA;
// Read in size, and any hidden stuff
s.defaultReadObject();
// Read in capacity
s.readInt(); // ignored
if (size > 0) {
// be like clone(), allocate array based upon size not capacity
int capacity = calculateCapacity(elementData, size);
SharedSecrets.getJavaOISAccess().checkArray(s, Object[].class, capacity);
ensureCapacityInternal(size);
Object[] a = elementData;
// Read in all elements in the proper order.
for (int i=0; i<size; i++) {
a[i] = s.readObject();
}
}
}
/**
* Returns a list iterator over the elements in this list (in proper
* sequence), starting at the specified position in the list.
* The specified index indicates the first element that would be
* returned by an initial call to {@link ListIterator#next next}.
* An initial call to {@link ListIterator#previous previous} would
* return the element with the specified index minus one.
*
* <p>The returned list iterator is <a href="#fail-fast"><i>fail-fast</i></a>.
*
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
public ListIterator<E> listIterator(int index) {
if (index < 0 || index > size)
throw new IndexOutOfBoundsException("Index: "+index);
return new ListItr(index);
}
/**
* Returns a list iterator over the elements in this list (in proper
* sequence).
*
* <p>The returned list iterator is <a href="#fail-fast"><i>fail-fast</i></a>.
*
* @see #listIterator(int)
*/
public ListIterator<E> listIterator() {
return new ListItr(0);
}
/**
* Returns an iterator over the elements in this list in proper sequence.
*
* <p>The returned iterator is <a href="#fail-fast"><i>fail-fast</i></a>.
*
* @return an iterator over the elements in this list in proper sequence
*/
public Iterator<E> iterator() {
return new Itr();
}
/**
* An optimized version of AbstractList.Itr
*/
private class Itr implements Iterator<E> {
int cursor; // index of next element to return
int lastRet = -1; // index of last element returned; -1 if no such
int expectedModCount = modCount;
Itr() {}
public boolean hasNext() {
return cursor != size;
}
@SuppressWarnings("unchecked")
public E next() {
checkForComodification();
int i = cursor;
if (i >= size)
throw new NoSuchElementException();
Object[] elementData = ArrayList.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 {
ArrayList.this.remove(lastRet);
cursor = lastRet;
lastRet = -1;
expectedModCount = modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
@Override
@SuppressWarnings("unchecked")
public void forEachRemaining(Consumer<? super E> consumer) {
Objects.requireNonNull(consumer);
final int size = ArrayList.this.size;
int i = cursor;
if (i >= size) {
return;
}
final Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length) {
throw new ConcurrentModificationException();
}
while (i != size && modCount == expectedModCount) {
consumer.accept((E) elementData[i++]);
}
// update once at end of iteration to reduce heap write traffic
cursor = i;
lastRet = i - 1;
checkForComodification();
}
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}
/**
* An optimized version of AbstractList.ListItr
*/
private class ListItr extends Itr implements ListIterator<E> {
ListItr(int index) {
super();
cursor = index;
}
public boolean hasPrevious() {
return cursor != 0;
}
public int nextIndex() {
return cursor;
}
public int previousIndex() {
return cursor - 1;
}
@SuppressWarnings("unchecked")
public E previous() {
checkForComodification();
int i = cursor - 1;
if (i < 0)
throw new NoSuchElementException();
Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length)
throw new ConcurrentModificationException();
cursor = i;
return (E) elementData[lastRet = i];
}
public void set(E e) {
if (lastRet < 0)
throw new IllegalStateException();
checkForComodification();
try {
ArrayList.this.set(lastRet, e);
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
public void add(E e) {
checkForComodification();
try {
int i = cursor;
ArrayList.this.add(i, e);
cursor = i + 1;
lastRet = -1;
expectedModCount = modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
}
/**
* Returns a view of the portion of this list between the specified
* {@code fromIndex}, inclusive, and {@code toIndex}, exclusive. (If
* {@code fromIndex} and {@code toIndex} are equal, the returned list is
* empty.) The returned list is backed by this list, so non-structural
* changes in the returned list are reflected in this list, and vice-versa.
* The returned list supports all of the optional list operations.
*
* <p>This method eliminates the need for explicit range operations (of
* the sort that commonly exist for arrays). Any operation that expects
* a list can be used as a range operation by passing a subList view
* instead of a whole list. For example, the following idiom
* removes a range of elements from a list:
* <pre>
* list.subList(from, to).clear();
* </pre>
* Similar idioms may be constructed for {@link #indexOf(Object)} and
* {@link #lastIndexOf(Object)}, and all of the algorithms in the
* {@link Collections} class can be applied to a subList.
*
* <p>The semantics of the list returned by this method become undefined if
* the backing list (i.e., this list) is <i>structurally modified</i> in
* any way other than via the returned list. (Structural modifications are
* those that change the size of this list, or otherwise perturb it in such
* a fashion that iterations in progress may yield incorrect results.)
*
* @throws IndexOutOfBoundsException {@inheritDoc}
* @throws IllegalArgumentException {@inheritDoc}
*/
public List<E> subList(int fromIndex, int toIndex) {
subListRangeCheck(fromIndex, toIndex, size);
return new SubList(this, 0, fromIndex, toIndex);
}
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 IllegalArgumentException("fromIndex(" + fromIndex +
") > toIndex(" + toIndex + ")");
}
private class SubList extends AbstractList<E> implements RandomAccess {
private final AbstractList<E> parent;
private final int parentOffset;
private final int offset;
int size;
SubList(AbstractList<E> parent,
int offset, int fromIndex, int toIndex) {
this.parent = parent;
this.parentOffset = fromIndex;
this.offset = offset + fromIndex;
this.size = toIndex - fromIndex;
this.modCount = ArrayList.this.modCount;
}
public E set(int index, E e) {
rangeCheck(index);
checkForComodification();
E oldValue = ArrayList.this.elementData(offset + index);
ArrayList.this.elementData[offset + index] = e;
return oldValue;
}
public E get(int index) {
rangeCheck(index);
checkForComodification();
return ArrayList.this.elementData(offset + index);
}
public int size() {
checkForComodification();
return this.size;
}
public void add(int index, E e) {
rangeCheckForAdd(index);
checkForComodification();
parent.add(parentOffset + index, e);
this.modCount = parent.modCount;
this.size++;
}
public E remove(int index) {
rangeCheck(index);
checkForComodification();
E result = parent.remove(parentOffset + index);
this.modCount = parent.modCount;
this.size--;
return result;
}
protected void removeRange(int fromIndex, int toIndex) {
checkForComodification();
parent.removeRange(parentOffset + fromIndex,
parentOffset + toIndex);
this.modCount = parent.modCount;
this.size -= toIndex - fromIndex;
}
public boolean addAll(Collection<? extends E> c) {
return addAll(this.size, c);
}
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;
}
public Iterator<E> iterator() {
return listIterator();
}
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 = ArrayList.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[] elementData = ArrayList.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 = ArrayList.this.elementData;
if (offset + i >= elementData.length)
throw new ConcurrentModificationException();
cursor = i;
return (E) elementData[offset + (lastRet = 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++)]);
}
// update once at end of iteration to reduce heap write traffic
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 = ArrayList.this.modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
public void set(E e) {
if (lastRet < 0)
throw new IllegalStateException();
checkForComodification();
try {
ArrayList.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 = ArrayList.this.modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
final void checkForComodification() {
if (expectedModCount != ArrayList.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 (ArrayList.this.modCount != this.modCount)
throw new ConcurrentModificationException();
}
public Spliterator<E> spliterator() {
checkForComodification();
return new ArrayListSpliterator<E>(ArrayList.this, offset,
offset + this.size, this.modCount);
}
}
/**
* Consumer 消费者 加入参数进行处理 不返回任何值 accept(T t)方法
*/
@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();
}
}
/**
* Creates a <em><a href="Spliterator.html#binding">late-binding</a></em>
* and <em>fail-fast</em> {@link Spliterator} over the elements in this
* list.
*
* <p>The {@code Spliterator} reports {@link Spliterator#SIZED},
* {@link Spliterator#SUBSIZED}, and {@link Spliterator#ORDERED}.
* Overriding implementations should document the reporting of additional
* characteristic values.
*
* @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);
}
/** Index-based split-by-two, lazily initialized Spliterator */
static final class ArrayListSpliterator<E> implements Spliterator<E> {
/*
* If ArrayLists were immutable, or structurally immutable (no
* adds, removes, etc), we could implement their spliterators
* with Arrays.spliterator. Instead we detect as much
* interference during traversal as practical without
* sacrificing much performance. We rely primarily on
* modCounts. These are not guaranteed to detect concurrency
* violations, and are sometimes overly conservative about
* within-thread interference, but detect enough problems to
* be worthwhile in practice. To carry this out, we (1) lazily
* initialize fence and expectedModCount until the latest
* point that we need to commit to the state we are checking
* against; thus improving precision. (This doesn't apply to
* SubLists, that create spliterators with current non-lazy
* values). (2) We perform only a single
* ConcurrentModificationException check at the end of forEach
* (the most performance-sensitive method). When using forEach
* (as opposed to iterators), we can normally only detect
* interference after actions, not before. Further
* CME-triggering checks apply to all other possible
* violations of assumptions for example null or too-small
* elementData array given its size(), that could only have
* occurred due to interference. This allows the inner loop
* of forEach to run without any further checks, and
* simplifies lambda-resolution. While this does entail a
* number of checks, note that in the common case of
* list.stream().forEach(a), no checks or other computation
* occur anywhere other than inside forEach itself. The other
* less-often-used methods cannot take advantage of most of
* these streamlinings.
*/
private final ArrayList<E> list;
private int index; // current index, modified on advance/split
private int fence; // -1 until used; then one past last index
private int expectedModCount; // initialized when fence set
/** Create new spliterator covering the given range */
ArrayListSpliterator(ArrayList<E> list, int origin, int fence,
int expectedModCount) {
this.list = list; // OK if null unless traversed
this.index = origin;
this.fence = fence;
this.expectedModCount = expectedModCount;
}
private int getFence() { // initialize fence to size on first use
int hi; // (a specialized variant appears in method forEach)
ArrayList<E> lst;
if ((hi = fence) < 0) {
if ((lst = list) == null)
hi = fence = 0;
else {
expectedModCount = lst.modCount;
hi = fence = lst.size;
}
}
return hi;
}
public ArrayListSpliterator<E> trySplit() {
int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
return (lo >= mid) ? null : // divide range in half unless too small
new ArrayListSpliterator<E>(list, lo, index = mid,
expectedModCount);
}
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 != expectedModCount)
throw new ConcurrentModificationException();
return true;
}
return false;
}
public void forEachRemaining(Consumer<? super E> action) {
int i, hi, mc; // hoist accesses and checks from loop
ArrayList<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 = expectedModCount;
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();
}
public long estimateSize() {
return (long) (getFence() - index);
}
public int characteristics() {
return Spliterator.ORDERED | Spliterator.SIZED | Spliterator.SUBSIZED;
}
}
@Override
public boolean removeIf(Predicate<? super E> filter) {
Objects.requireNonNull(filter);
// figure out which elements are to be removed
// any exception thrown from the filter predicate at this stage
// will leave the collection unmodified
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();
}
// shift surviving elements left over the spaces left by removed elements
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; // Let gc do its work
}
this.size = newSize;
if (modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
modCount++;
}
return anyToRemove;
}
@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++;
}
@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++;
}
}
##ArrayList小结
一.正确遍历删除元素的相关问题a(1,2,3,4,5)
1.for(int i : a) a.remove(1) 报java.util.ConcurrentModificationException
ArrayList$Itr.next方法的checkForComodification 方法 if (i >= elementData.length)检查修改次数与期望的修改次数不相同
2. Iterator<Integer> iterator = a.iterator();
while(iterator.hasNext()){
a.remove(iterator.next());
} 报java.util.ConcurrentModificationException 第一次remove 是可以的,但是iterator的期望修改次数 没变,但是modcount+1 了,所以next()方法的时候 报错
ArrayList$Itr.next方法的checkForComodification 方法 if (i >= elementData.length) 检查修改次数与期望的修改次数不相同
3. Iterator<Integer> iterator = a.iterator();
while(iterator.hasNext()){
iterator.remove();
} 报 java.lang.IllegalStateException
4. Iterator<Integer> iterator = a.iterator();
while(iterator.hasNext()){
int c = iterator.next(); //比3 多一个这个方法 next中 将lastRet 设置为游标大于0
iterator.remove();
} 正常删除
5. for(int i = a.size()-1 ; i >=0 ;i--){
a.remove(i);
} 正常删除 遍历 从大到小 删除 注意i的取值范围
##ArrayList 案例解析
package com.mk.coffee.test.jdk.resource.demo20190118;
import java.util.ArrayList;
/**
* @Auther: makui
* @Date: 2019/1/18
* @Description:
*/
public class ArrayListDemo {
public static void main(String[] args) {
ArrayList s = new ArrayList(); //1. 创建一个ArrayList()数组队列
s.add(3);
s.add("3");
s.add(new Integer(44));
boolean b = s.removeIf(v -> v.equals(2));
System.out.println(s.toString());
boolean a = s.removeIf(v -> v.equals(3));
boolean c = s.removeIf(v -> v.equals(3));
System.out.println(c);
System.out.println(s.toString());
}
}
重点解析:
1.ArrayList s = new ArrayList(); 当执行new ArrayList()时,调用了ArrayList的无参构造器。
无参构造器 public ArrayList(){
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA; //{}为空数组
},此时数组队列对象 为{} , size为0,容量为0。
2.s.add(3); 调用了boolean add(E e){
ensureCapacityInternal(size + 1); // Increments modCount!! 首先确认当前最小容量可以使用,不行的话扩容,扩展数组的大小。容量在第一次新增的时候,会默认10。之后如果10不够的话,就需要扩容。 grow()扩容 oldcapatity + lodcapatity >> 1 大概1.5倍
elementData[size++] = e; //将新增元素 添加到数组elementData最后的位置。
return true;
}
#Spliterator源码
package java.util;
import java.util.function.Consumer;
import java.util.function.DoubleConsumer;
import java.util.function.IntConsumer;
import java.util.function.LongConsumer;
/*
* 可分割的迭代器
* @see Collection
* @since 1.8
*/
public interface Spliterator<T> {
//如果剩下的元素存在,执行给定的操作,返回true ; 否则返回false 。
boolean tryAdvance(Consumer<? super T> action);
//在当前线程中依次执行每个剩余元素的给定操作,直到所有元素都被处理或动作引发异常
default void forEachRemaining(Consumer<? super T> action) {
do { } while (tryAdvance(action));
}
//如果此分割器可以被分区,返回一个包含元素的Spliter,当从该方法返回时,它不会被该Spliter所覆盖。
Spliterator<T> trySplit();
////用于估算还剩下多少个元素需要遍历
long estimateSize();
////当迭代器拥有SIZED特征时,返回剩余元素个数;否则返回-1
default long getExactSizeIfKnown() {
return (characteristics() & SIZED) == 0 ? -1L : estimateSize();
}
///返回此Spliterator及其元素的一组特征。
int characteristics();
//如果Spliterator的 characteristics()包含所有给定的特性,返回 true
default boolean hasCharacteristics(int characteristics) {
return (characteristics() & characteristics) == characteristics;
}
//如果Spliterator的list是通过Comparator排序的,则返回Comparator
//如果Spliterator的list是自然排序的 ,则返回null
//其他情况下抛错
default Comparator<? super T> getComparator() {
throw new IllegalStateException();
}
//特征值表示为元素定义遇到顺序。
public static final int ORDERED = 0x00000010;
//特性值这标志着,对于每对遇到的元件 x, y , !x.equals(y) 。
public static final int DISTINCT = 0x00000001;
//特征值表示遇到的顺序遵循定义的排序顺序
public static final int SORTED = 0x00000004;
//表示在遍历或 estimateSize()之前从 estimateSize()返回的值的特征值表示在没有结构源修改的情况下表示完全遍历将遇到的元素数量的精确计数的有限大小。
public static final int SIZED = 0x00000040;
//特征值表示源保证遇到的元素不会为 null 。
public static final int NONNULL = 0x00000100;
//特征值表示元素源不能在结构上进行修改; 也就是说,不能添加,替换或删除元素,因此在遍历过程中不会发生这种更改。
public static final int IMMUTABLE = 0x00000400;
//特征值表示可以通过多个线程安全同时修改元素源(允许添加,替换和/或删除),而无需外部同步。
public static final int CONCURRENT = 0x00001000;
//特征值这标志着从产生的所有Spliterators trySplit()将是既 SIZED和 SUBSIZED 。
public static final int SUBSIZED = 0x00004000;
public interface OfPrimitive<T, T_CONS, T_SPLITR extends Spliterator.OfPrimitive<T, T_CONS, T_SPLITR>>
extends Spliterator<T> {
@Override
T_SPLITR trySplit();
@SuppressWarnings("overloads")
boolean tryAdvance(T_CONS action);
@SuppressWarnings("overloads")
default void forEachRemaining(T_CONS action) {
do { } while (tryAdvance(action));
}
}
public interface OfInt extends OfPrimitive<Integer, IntConsumer, OfInt> {
@Override
OfInt trySplit();
@Override
boolean tryAdvance(IntConsumer action);
@Override
default void forEachRemaining(IntConsumer action) {
do { } while (tryAdvance(action));
}
@Override
default boolean tryAdvance(Consumer<? super Integer> action) {
if (action instanceof IntConsumer) {
return tryAdvance((IntConsumer) action);
}
else {
if (Tripwire.ENABLED)
Tripwire.trip(getClass(),
"{0} calling Spliterator.OfInt.tryAdvance((IntConsumer) action::accept)");
return tryAdvance((IntConsumer) action::accept);
}
}
@Override
default void forEachRemaining(Consumer<? super Integer> action) {
if (action instanceof IntConsumer) {
forEachRemaining((IntConsumer) action);
}
else {
if (Tripwire.ENABLED)
Tripwire.trip(getClass(),
"{0} calling Spliterator.OfInt.forEachRemaining((IntConsumer) action::accept)");
forEachRemaining((IntConsumer) action::accept);
}
}
}
/**
* A Spliterator specialized for {@code long} values.
* @since 1.8
*/
public interface OfLong extends OfPrimitive<Long, LongConsumer, OfLong> {
@Override
OfLong trySplit();
@Override
boolean tryAdvance(LongConsumer action);
@Override
default void forEachRemaining(LongConsumer action) {
do { } while (tryAdvance(action));
}
@Override
default boolean tryAdvance(Consumer<? super Long> action) {
if (action instanceof LongConsumer) {
return tryAdvance((LongConsumer) action);
}
else {
if (Tripwire.ENABLED)
Tripwire.trip(getClass(),
"{0} calling Spliterator.OfLong.tryAdvance((LongConsumer) action::accept)");
return tryAdvance((LongConsumer) action::accept);
}
}
@Override
default void forEachRemaining(Consumer<? super Long> action) {
if (action instanceof LongConsumer) {
forEachRemaining((LongConsumer) action);
}
else {
if (Tripwire.ENABLED)
Tripwire.trip(getClass(),
"{0} calling Spliterator.OfLong.forEachRemaining((LongConsumer) action::accept)");
forEachRemaining((LongConsumer) action::accept);
}
}
}
/**
* A Spliterator specialized for {@code double} values.
* @since 1.8
*/
public interface OfDouble extends OfPrimitive<Double, DoubleConsumer, OfDouble> {
@Override
OfDouble trySplit();
@Override
boolean tryAdvance(DoubleConsumer action);
@Override
default void forEachRemaining(DoubleConsumer action) {
do { } while (tryAdvance(action));
}
@Override
default boolean tryAdvance(Consumer<? super Double> action) {
if (action instanceof DoubleConsumer) {
return tryAdvance((DoubleConsumer) action);
}
else {
if (Tripwire.ENABLED)
Tripwire.trip(getClass(),
"{0} calling Spliterator.OfDouble.tryAdvance((DoubleConsumer) action::accept)");
return tryAdvance((DoubleConsumer) action::accept);
}
}
@Override
default void forEachRemaining(Consumer<? super Double> action) {
if (action instanceof DoubleConsumer) {
forEachRemaining((DoubleConsumer) action);
}
else {
if (Tripwire.ENABLED)
Tripwire.trip(getClass(),
"{0} calling Spliterator.OfDouble.forEachRemaining((DoubleConsumer) action::accept)");
forEachRemaining((DoubleConsumer) action::accept);
}
}
}
}