publicinterfaceIterable<T> { /** * Returns an iterator over elements of type {@code T}. * * @return an Iterator. */ //返回一个迭代器,Iterator是真正的迭代器实现,而Iterable则是表示一种能力(able形容词)——迭代的能力。 Iterator<T> iterator(); ...... }
publicinterfaceIterator<E> { /** * Returns {@code true} if the iteration has more elements. * (In other words, returns {@code true} if {@link #next} would * return an element rather than throwing an exception.) * * @return {@code true} if the iteration has more elements */ booleanhasNext();
/** * Returns the next element in the iteration. * * @return the next element in the iteration * @throws NoSuchElementException if the iteration has no more elements */ E next(); ...... }
// 获取index元素 E elementData(int index){ return (E) elementData[index]; }
privateclassItrimplementsIterator<E> { int cursor; // index of next element to return //即将遍历的元素的索引 int lastRet = -1; // index of last element returned; -1 if no such //记录刚刚遍历过的元素的索引 int expectedModCount = modCount; // 记录操作次数,用来支持 fast fail机制,在迭代时不能修改容器 publicbooleanhasNext(){ // cursor == elementCount表示遍历到尾部 return cursor != elementCount; }
public E next(){ // 锁Vector对象,保证不同的线程使用不同的迭代器操作同一Vector,同步执行 synchronized (Vector.this) { // fast fail 机制,检查容器是否被修改 checkForComodification(); int i = cursor; if (i >= elementCount) thrownew NoSuchElementException(); cursor = i + 1; // 获取下一个cursor,并设置lastRet return elementData(lastRet = i); } }
privateclassItrimplementsIterator<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() {}
publicbooleanhasNext(){ return cursor != size; }
@SuppressWarnings("unchecked") public E next(){ checkForComodification(); int i = cursor; if (i >= size) thrownew NoSuchElementException(); Object[] elementData = ArrayList.this.elementData; if (i >= elementData.length) thrownew ConcurrentModificationException(); cursor = i + 1; return (E) elementData[lastRet = i]; }
publicvoidremove(){ if (lastRet < 0) thrownew IllegalStateException(); checkForComodification();
@SuppressWarnings("unchecked") public E previous(){ checkForComodification(); int i = cursor - 1; if (i < 0) thrownew NoSuchElementException(); Object[] elementData = ArrayList.this.elementData; if (i >= elementData.length) thrownew ConcurrentModificationException(); cursor = i; return (E) elementData[lastRet = i]; }
publicvoidset(E e){ if (lastRet < 0) thrownew IllegalStateException(); checkForComodification();
public E next(){ // fast fail机制,后面就不再提了 checkForComodification(); if (!hasNext()) thrownew NoSuchElementException(); // 更新lastReture next nextIndex lastReturned = next; next = next.next; nextIndex++; return lastReturned.item; }
public E previous(){ checkForComodification(); if (!hasPrevious()) thrownew NoSuchElementException(); // next == null 说明初始化index为size ->查看构造函数 lastReturned = next = (next == null) ? last : next.prev; nextIndex--; return lastReturned.item; }
staticclassNode<K,V> implementsMap.Entry<K,V> { finalint hash; final K key; V value; Node<K,V> next; // 省略方法... }
abstractclassHashIterator{ // 其实可以把next理解成当前节点,current理解成lastReturned节点,像之前那样 Node<K,V> next; // next entry to return Node<K,V> current; // current entry int expectedModCount; // for fast-fail int index; // current slot 桶索引
HashIterator() { expectedModCount = modCount; Node<K,V>[] t = table; current = next = null; index = 0; if (t != null && size > 0) { // advance to first entry // 初始化next,找到第一个不为空的桶,next引用其第一个节点 do {} while (index < t.length && (next = t[index++]) == null); } }
publicfinalbooleanhasNext(){ return next != null; }
final Node<K,V> nextNode(){ Node<K,V>[] t; Node<K,V> e = next; if (modCount != expectedModCount) thrownew ConcurrentModificationException(); if (e == null) thrownew NoSuchElementException(); // ******************核心*********************** // 更新current的值为next,next为更新后current的next // 如果next为空,说明当前桶遍历完毕,进入下一个 if ((next = (current = e).next) == null && (t = table) != null) { // 找到下一个不为空的桶,next引用其第一个节点 do {} while (index < t.length && (next = t[index++]) == null); } // ******************核心*********************** return e; }
// 移除current节点 publicfinalvoidremove(){ Node<K,V> p = current; if (p == null) thrownew IllegalStateException(); if (modCount != expectedModCount) thrownew ConcurrentModificationException(); current = null; K key = p.key; // 调用HashMap的removeNode方法 removeNode(hash(key), key, null, false, false); expectedModCount = modCount; } }
publicfinalbooleanhasNext(){ return next != null; }
final Entry<K,V> nextEntry(){ Entry<K,V> e = next; if (e == null) thrownew NoSuchElementException(); if (modCount != expectedModCount) thrownew ConcurrentModificationException(); // 找到后继节点 next = successor(e); lastReturned = e; return e; }
final Entry<K,V> prevEntry(){ Entry<K,V> e = next; if (e == null) thrownew NoSuchElementException(); if (modCount != expectedModCount) thrownew ConcurrentModificationException(); // 找到前驱节点 next = predecessor(e); lastReturned = e; return e; }
publicvoidremove(){ if (lastReturned == null) thrownew IllegalStateException(); if (modCount != expectedModCount) thrownew ConcurrentModificationException(); // 删除上一个返回的节点 // 如果他有一个孩子,则子树则会替代他的位置 // 如果他有两个孩子,则会使其后继节点(右子树的最左孩子)替代他的位置,就需要调整next引用到lastReturned // deleted entries are replaced by their successors if (lastReturned.left != null && lastReturned.right != null) next = lastReturned; deleteEntry(lastReturned); expectedModCount = modCount; lastReturned = null; } }
// 下面是获取迭代器的方法
// TreeMap.EntrySet public Iterator<Map.Entry<K,V>> iterator() { returnnew EntryIterator(getFirstEntry()); }
publicbooleancontains(Object o){ // 使用迭代器实现 Iterator<E> it = iterator(); if (o==null) { while (it.hasNext()) if (it.next()==null) returntrue; } else { while (it.hasNext()) if (o.equals(it.next())) returntrue; } returnfalse; }
public Object[] toArray() { // 这里的size只是估计值 Object[] r = new Object[size()]; Iterator<E> it = iterator(); for (int i = 0; i < r.length; i++) { if (! it.hasNext()) // i还在循环,但是迭代器却没有下一个元素了,说明有并发remove操作,返回数组副本 return Arrays.copyOf(r, i); r[i] = it.next(); } // i遍历结束,迭代器还有下一个,说明有并发add操作,扩容,并将剩余元素添加到数组中 // 否则,返回数组 return it.hasNext() ? finishToArray(r, it) : r; }
@SuppressWarnings("unchecked") public <T> T[] toArray(T[] a) { int size = size(); // 判断a的大小,不满足则利用反射创建新数组 T[] r = a.length >= size ? a : (T[])java.lang.reflect.Array .newInstance(a.getClass().getComponentType(), size); Iterator<E> it = iterator(); for (int i = 0; i < r.length; i++) { // i还在循环,但是迭代器却没有下一个元素了,说明有并发remove操作 if (! it.hasNext()) { // 如果没有创建新数组,最后一个元素置null,返回a if (a == r) { r[i] = null; // null-terminate // 如果创建了新数组,并且当前数组长度大于a的长度,返回当前数组副本 } elseif (a.length < i) { return Arrays.copyOf(r, i); // 如果创建了新数组,并且当前数组长度小于a的长度,将当前数组拷贝给a } else { System.arraycopy(r, 0, a, 0, i); // 如果a数组没有用完,最后一个元素置null,返回a if (a.length > i) { a[i] = null; } } return a; } r[i] = (T)it.next(); } // i遍历结束,迭代器还有下一个,说明有并发add操作,扩容,并将剩余元素添加到数组中 // 否则,返回数组 return it.hasNext() ? finishToArray(r, it) : r; }
/** * 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.MAX_VALUE - 8 // 有的虚拟机实现,数组对象的头部会占用这8个字节 privatestaticfinalint MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
// 扩容,并将迭代器剩余元素添加到数组中 @SuppressWarnings("unchecked") privatestatic <T> T[] finishToArray(T[] r, Iterator<?> it) { // 当前数组索引,从数组尾开始 int i = r.length; while (it.hasNext()) { // cap为数组长度 int cap = r.length; // 当前数组索引等于数组长度,扩容 if (i == cap) { // 扩容大小 newCap = cap * 1.5 + 1 int newCap = cap + (cap >> 1) + 1; // 保证数组最大长度 if (newCap - MAX_ARRAY_SIZE > 0) newCap = hugeCapacity(cap + 1); // 扩容 r = Arrays.copyOf(r, newCap); } // 迭代,添加到数组中 r[i++] = (T)it.next(); } // 如果当前索引等于数组长度,说明数组刚好用完,返回数组。否则,按照当前长度返回数组副本 return (i == r.length) ? r : Arrays.copyOf(r, i); }
// 移除o publicbooleanremove(Object o){ Iterator<E> it = iterator(); if (o==null) { while (it.hasNext()) { if (it.next()==null) { it.remove(); returntrue; } } } else { while (it.hasNext()) { if (o.equals(it.next())) { it.remove(); returntrue; } } } returnfalse; }
// 如果此集合中包含c中所有元素,返回true publicbooleancontainsAll(Collection<?> c){ for (Object e : c) if (!contains(e)) returnfalse; returntrue; }
// 添加c中元素到此集合中 publicbooleanaddAll(Collection<? extends E> c){ boolean modified = false; for (E e : c) if (add(e)) modified = true; // 如果此集合改变,返回true return modified; }
// 暂时不管 defaultvoidreplaceAll(UnaryOperator<E> operator){ Objects.requireNonNull(operator); final ListIterator<E> li = this.listIterator(); while (li.hasNext()) { li.set(operator.apply(li.next())); } }
// 修改index索引对应元素 E set(int index, E element);
// 排序的实现,个人感觉效率有点低。先获取数组,然后调用Arrays工具类排序,再用迭代器将排序后的元素set回去 // 我们发现Collections工具类的sort方法就是调用的这个方法来实现的。 defaultvoidsort(Comparator<? super E> c){ Object[] a = this.toArray(); Arrays.sort(a, (Comparator) c); ListIterator<E> i = this.listIterator(); for (Object e : a) { i.next(); i.set((E) e); } }
// 返回从fromIndex索引到toIndex索引的列表的视图,下面会说到他的实现 List<E> subList(int fromIndex, int toIndex);
7.2 实现类AbstractList
publicbooleanequals(Object o){ if (o == this) returntrue; if (!(o instanceof List)) returnfalse;
// 从前往后,查找指定元素索引,没有返回-1 publicintindexOf(Object o){ ListIterator<E> it = listIterator(); if (o==null) { while (it.hasNext()) if (it.next()==null) return it.previousIndex(); } else { while (it.hasNext()) if (o.equals(it.next())) return it.previousIndex(); } return -1; }
// 从后往前,查找指定元素索引,没有返回-1 publicintlastIndexOf(Object o){ ListIterator<E> it = listIterator(size()); if (o==null) { while (it.hasPrevious()) if (it.previous()==null) return it.nextIndex(); } else { while (it.hasPrevious()) if (o.equals(it.previous())) return it.nextIndex(); } return -1; }
// 获取迭代器 public Iterator<E> iterator(){ returnnew Itr(); }
public ListIterator<E> listIterator(){ return listIterator(0); }
public ListIterator<E> listIterator(finalint index){ rangeCheckForAdd(index);
returnnew ListItr(index); }
// 不支持remove、set方法 public E remove(int index){ thrownew UnsupportedOperationException(); }
public E set(int index, E element){ thrownew UnsupportedOperationException(); }
// 返回从fromIndex索引到toIndex索引的列表的视图 // 这里根据RandomAccess进行了一个区分,之前的博客分析过,RandomAccess是支持随机访问的 public List<E> subList(int fromIndex, int toIndex){ return (thisinstanceof RandomAccess ? new RandomAccessSubList<>(this, fromIndex, toIndex) : new SubList<>(this, fromIndex, toIndex)); }
// 还有三个工具方法 // 删除从索引fromIndex到toIndex的元素 protectedvoidremoveRange(int fromIndex, int toIndex){ ListIterator<E> it = listIterator(fromIndex); for (int i=0, n=toIndex-fromIndex; i<n; i++) { it.next(); it.remove(); } }
// 判断index合法性 privatevoidrangeCheckForAdd(int index){ if (index < 0 || index > size()) thrownew IndexOutOfBoundsException(outOfBoundsMsg(index)); }
SubList(AbstractList<E> list, int fromIndex, int toIndex) { if (fromIndex < 0) thrownew IndexOutOfBoundsException("fromIndex = " + fromIndex); if (toIndex > list.size()) thrownew IndexOutOfBoundsException("toIndex = " + toIndex); if (fromIndex > toIndex) thrownew IllegalArgumentException("fromIndex(" + fromIndex + ") > toIndex(" + toIndex + ")"); l = list; offset = fromIndex; size = toIndex - fromIndex; this.modCount = l.modCount; }
/**************************************************************************/ /*下面的方法,封装了父列表的相关方法,进行相关检查,考虑offset,修改size、modCount,以适应视图*/ public E set(int index, E element){ rangeCheck(index); checkForComodification(); return l.set(index+offset, element); }
public E get(int index){ rangeCheck(index); checkForComodification(); return l.get(index+offset); }
public E remove(int index){ rangeCheck(index); checkForComodification(); E result = l.remove(index+offset); this.modCount = l.modCount; size--; return result; }