Java编程中ArrayList源码分析
程序员文章站
2023-12-02 20:07:40
之前看过一句话,说的特别好。有人问阅读源码有什么用?学习别人实现某个功能的设计思路,提高自己的编程水平。
是的,大家都实现一个功能,不同的人有不同的设计思路,有的人用一万...
之前看过一句话,说的特别好。有人问阅读源码有什么用?学习别人实现某个功能的设计思路,提高自己的编程水平。
是的,大家都实现一个功能,不同的人有不同的设计思路,有的人用一万行代码,有的人用五千行。有的人代码运行需要的几十秒,有的人只需要的几秒。。下面进入正题了。
本文的主要内容:
· 详细注释了arraylist的实现,基于jdk 1.8 。
·迭代器sublist部分未详细解释,会放到其他源码解读里面。此处重点关注arraylist本身实现。
·没有采用标准的注释,并适当调整了代码的缩进以方便介绍
import java.util.abstractlist; import java.util.arrays; import java.util.bitset; import java.util.collection; import java.util.comparator; import java.util.concurrentmodificationexception; import java.util.iterator; import java.util.list; import java.util.listiterator; import java.util.nosuchelementexception; import java.util.objects; import java.util.randomaccess; import java.util.spliterator; import java.util.function.consumer; import java.util.function.predicate; import java.util.function.unaryoperator; /** * 概述: * list接口可调整大小的数组实现。实现所有可选的list操作,并允许所有元素,包括null,元素可重复。 * 除了列表接口外,该类提供了一种方法来操作该数组的大小来存储该列表中的数组的大小。 * * 时间复杂度: * 方法size、isempty、get、set、iterator和listiterator的调用是常数时间的。 * 添加删除的时间复杂度为o(n)。其他所有操作也都是线性时间复杂度。 * * 容量: * 每个arraylist都有容量,容量大小至少为list元素的长度,默认初始化为10。 * 容量可以自动增长。 * 如果提前知道数组元素较多,可以在添加元素前通过调用ensurecapacity()方法提前增加容量以减小后期容量自动增长的开销。 * 也可以通过带初始容量的构造器初始化这个容量。 * * 线程不安全: * arraylist不是线程安全的。 * 如果需要应用到多线程中,需要在外部做同步 * * modcount: * 定义在abstractlist中:protected transient int modcount = 0; * 已从结构上修改此列表的次数。从结构上修改是指更改列表的大小,或者打乱列表,从而使正在进行的迭代产生错误的结果。 * 此字段由iterator和listiterator方法返回的迭代器和列表迭代器实现使用。 * 如果意外更改了此字段中的值,则迭代器(或列表迭代器)将抛出concurrentmodificationexception来响应next、remove、previous、set或add操作。 * 在迭代期间面临并发修改时,它提供了快速失败 行为,而不是非确定性行为。 * 子类是否使用此字段是可选的。 * 如果子类希望提供快速失败迭代器(和列表迭代器),则它只需在其 add(int,e)和remove(int)方法(以及它所重写的、导致列表结构上修改的任何其他方法)中增加此字段。 * 对add(int, e)或remove(int)的单个调用向此字段添加的数量不得超过 1,否则迭代器(和列表迭代器)将抛出虚假的 concurrentmodificationexceptions。 * 如果某个实现不希望提供快速失败迭代器,则可以忽略此字段。 * * transient: * 默认情况下,对象的所有成员变量都将被持久化.在某些情况下,如果你想避免持久化对象的一些成员变量,你可以使用transient关键字来标记他们,transient也是java中的保留字(jdk 1.8) */ public class arraylist<e> extends abstractlist<e> implements list<e>, randomaccess, cloneable, java.io.serializable { private static final long serialversionuid = 8683452581122892189l; //默认初始容量 private static final int default_capacity = 10; //用于空实例共享空数组实例。 private static final object[] empty_elementdata = {}; //默认的空数组 private static final object[] defaultcapacity_empty_elementdata = {}; //对的,存放元素的数组,包访问权限 transient object[] elementdata; //大小,创建对象时java会将int初始化为0 private int size; //用指定的数设置初始化容量的构造函数,负数会抛出异常 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); } } //默认构造函数,使用控数组初始化 public arraylist() { this.elementdata = defaultcapacity_empty_elementdata; } //以集合的迭代器返回顺序,构造一个含有集合中元素的列表 public arraylist(collection<? extends e> c) { elementdata = c.toarray(); if ((size = elementdata.length) != 0) { // c.toarray可能(错误地)不返回对象[](见java bug编号6260652) 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); } } //使用指定参数设置数组容量 public void ensurecapacity(int mincapacity) { //如果数组为空,容量预取0,否则去默认值(10) int minexpand = (elementdata != defaultcapacity_empty_elementdata)? 0: default_capacity; //若参数大于预设的容量,在使用该参数进一步设置数组容量 if (mincapacity > minexpand) { ensureexplicitcapacity(mincapacity); } } //用于添加元素时,确保数组容量 private void ensurecapacityinternal(int mincapacity) { //使用默认值和参数中较大者作为容量预设值 if (elementdata == defaultcapacity_empty_elementdata) { mincapacity = math.max(default_capacity, mincapacity); } ensureexplicitcapacity(mincapacity); } //如果参数大于数组容量,就增加数组容量 private void ensureexplicitcapacity(int mincapacity) { modcount++; if (mincapacity - elementdata.length > 0) grow(mincapacity); } //数组的最大容量,可能会导致内存溢出(vm内存限制) private static final int max_array_size = integer.max_value - 8; //增加容量,以确保它可以至少持有由参数指定的元素的数目 private void grow(int mincapacity) { int oldcapacity = elementdata.length; //预设容量增加一半 int newcapacity = oldcapacity + (oldcapacity >> 1); //取与参数中的较大值 if (newcapacity - mincapacity < 0)//即newcapacity<mincapacity newcapacity = mincapacity; //若预设值大于默认的最大值检查是否溢出 if (newcapacity - max_array_size > 0) newcapacity = hugecapacity(mincapacity); elementdata = arrays.copyof(elementdata, newcapacity); } //检查是否溢出,若没有溢出,返回最大整数值(java中的int为4字节,所以最大为0x7fffffff)或默认最大值 private static int hugecapacity(int mincapacity) { if (mincapacity < 0) //溢出 throw new outofmemoryerror(); return (mincapacity > max_array_size) ? integer.max_value : max_array_size; } //返回数组大小 public int size() { return size; } //是否为空 public boolean isempty() { return size == 0; } //是否包含一个数 返回bool public boolean contains(object o) { return indexof(o) >= 0; } //返回一个值在数组首次出现的位置,会根据是否为null使用不同方式判断。不存在就返回-1。时间复杂度为o(n) 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。时间复杂度为o(n) 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; } //返回副本,元素本身没有被复制,复制过程数组发生改变会抛出异常 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); } } //转换为object数组,使用arrays.copyof()方法 public object[] toarray() { return arrays.copyof(elementdata, size); } //返回一个数组,使用运行时确定类型,该数组包含在这个列表中的所有元素(从第一到最后一个元素) //返回的数组容量由参数和本数组中较大值确定 @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); if (a.length > size) a[size] = null; return a; } //返回指定位置的值,因为是数组,所以速度特别快 @suppresswarnings("unchecked") e elementdata(int index) { return (e) elementdata[index]; } //返回指定位置的值,但是会检查这个位置数否超出数组长度 public e get(int index) { rangecheck(index); return elementdata(index); } //设置指定位置为一个新值,并返回之前的值,会检查这个位置是否超出数组长度 public e set(int index, e element) { rangecheck(index); e oldvalue = elementdata(index); elementdata[index] = element; return oldvalue; } //添加一个值,首先会确保容量 public boolean add(e e) { ensurecapacityinternal(size + 1); elementdata[size++] = e; return true; } //指定位置添加一个值,会检查添加的位置和容量 public void add(int index, e element) { rangecheckforadd(index); ensurecapacityinternal(size + 1); //public static void arraycopy(object src, int srcpos, object dest, int destpos, int length) //src:源数组; srcpos:源数组要复制的起始位置; dest:目的数组; destpos:目的数组放置的起始位置; length:复制的长度 system.arraycopy(elementdata, index, elementdata, index + 1,size - index); elementdata[index] = element; size++; } //删除指定位置的值,会检查添加的位置,返回之前的值 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; // clear to let gc do its work } //清空数组,把每一个值设为null,方便垃圾回收(不同于reset,数组默认大小有改变的话不会重置) public void clear() { modcount++; for (int i = 0; i < size; i++) elementdata[i] = null; size = 0; } //添加一个集合的元素到末端,若要添加的集合为空返回false 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; } //删除指定范围元素。参数为开始删的位置和结束位置 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; } //检查数否超出数组长度 用于添加元素时 private void rangecheck(int index) { if (index >= size) throw new indexoutofboundsexception(outofboundsmsg(index)); } //检查是否溢出 private void rangecheckforadd(int index) { if (index > size || index < 0) throw new indexoutofboundsexception(outofboundsmsg(index)); } //抛出的异常的详情 private string outofboundsmsg(int index) { return "index: "+index+", size: "+size; } //删除指定集合的元素 public boolean removeall(collection<?> c) { objects.requirenonnull(c);//检查参数是否为null return batchremove(c, false); } //仅保留指定集合的元素 public boolean retainall(collection<?> c) { objects.requirenonnull(c); return batchremove(c, true); } /** * 源码解读 by http://anxpp.com/ * @param complement true时从数组保留指定集合中元素的值,为false时从数组删除指定集合中元素的值。 * @return 数组中重复的元素都会被删除(而不是仅删除一次或几次),有任何删除操作都会返回true */ private boolean batchremove(collection<?> c, boolean complement) { final object[] elementdata = this.elementdata; int r = 0, w = 0; boolean modified = false; try { //遍历数组,并检查这个集合是否包含对应的值,移动要保留的值到数组前面,w最后值为要保留的元素的数量 //简单点:若保留,就将相同元素移动到前段;若删除,就将不同元素移动到前段 for (; r < size; r++) if (c.contains(elementdata[r]) == complement) elementdata[w++] = elementdata[r]; }finally {//确保异常抛出前的部分可以完成期望的操作,而未被遍历的部分会被接到后面 //r!=size表示可能出错了:c.contains(elementdata[r])抛出异常 if (r != size) { system.arraycopy(elementdata, r,elementdata, w,size - r); w += size - r; } //如果w==size:表示全部元素都保留了,所以也就没有删除操作发生,所以会返回false;反之,返回true,并更改数组 //而w!=size的时候,即使try块抛出异常,也能正确处理异常抛出前的操作,因为w始终为要保留的前段部分的长度,数组也不会因此乱序 if (w != size) { for (int i = w; i < size; i++) elementdata[i] = null; modcount += size - w;//改变的次数 size = w; //新的大小为保留的元素的个数 modified = true; } } return modified; } //保存数组实例的状态到一个流(即它序列化)。写入过程数组被更改会抛出异常 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(); } } //上面是写,这个就是读了。 private void readobject(java.io.objectinputstream s) throws java.io.ioexception, classnotfoundexception { elementdata = empty_elementdata; // 执行默认的序列化/反序列化过程 s.defaultreadobject(); // 读入数组长度 s.readint(); if (size > 0) { ensurecapacityinternal(size); object[] a = elementdata; //读入所有元素 for (int i=0; i<size; i++) { a[i] = s.readobject(); } } } //返回listiterator,开始位置为指定参数 public listiterator<e> listiterator(int index) { if (index < 0 || index > size) throw new indexoutofboundsexception("index: "+index); return new listitr(index); } //返回listiterator,开始位置为0 public listiterator<e> listiterator() { return new listitr(0); } //返回普通迭代器 public iterator<e> iterator() { return new itr(); } //通用的迭代器实现 private class itr implements iterator<e> { int cursor; //游标,下一个元素的索引,默认初始化为0 int lastret = -1; //上次访问的元素的位置 int expectedmodcount = modcount;//迭代过程不运行修改数组,否则就抛出异常 //是否还有下一个 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++]); } cursor = i; lastret = i - 1; checkforcomodification(); } //检查数组是否被修改 final void checkforcomodification() { if (modcount != expectedmodcount) throw new concurrentmodificationexception(); } } //listiterator迭代器实现 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(); } } } //返回指定范围的子数组 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); } } @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" rel="external nofollow" >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++; } }
总结
以上就是本文关于java编程中arraylist源码分析的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!