资讯专栏INFORMATION COLUMN

JAVA基础集合框架【一】ArrayList之源码翻译-上

wean / 728人阅读

摘要:文章首发于基于的源码版权所有,和或其附属公司。使用须遵守许可条款。的迭代器会尽最大的努力抛出异常。因此,写程序依赖这个异常为了正确性这点是错误的,迭代器的行为仅仅被用来检查程序中的。这个类是集合框架的一员。

文章首发于:clawhub.club

基于 JDK1.8 的ArrayList源码:

/*
 * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved.
 * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 * 版权所有(c)1997,2017,Oracle和/或其附属公司。版权所有。
 * ORACLE 所有权/机密。使用须遵守许可条款。
 */

package java.util;

import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.function.UnaryOperator;
import sun.misc.SharedSecrets;

/**
 * Resizable-array implementation of the List interface.  Implements
 * all optional list operations, and permits all elements, including
 * null.  In addition to implementing the List interface,
 * this class provides methods to manipulate the size of the array that is
 * used internally to store the list.  (This class is roughly equivalent to
 * Vector, except that it is unsynchronized.)
 * 实现 List 接口的可变数组,实现了所有列表操作的方法,允许所有的元素,包括 null。
 * 除了实现 List 接口外,ArrayList 还提供了一些方法用来控制存储列表内部的数组大小。
 * (除了它不是同步的外,这个类相当于 Vector(类))
 * 
 * 
 * 

The size, isEmpty, get, set, * iterator, and listIterator operations run in constant * time. The add operation runs in amortized constant time, * that is, adding n elements requires O(n) time. All of the other operations * run in linear time (roughly speaking). The constant factor is low compared * to that for the LinkedList implementation. * size、isEmpty、get、set、iterator 和 listIterator 这些操作(方法)运行在恒定时间()。 * add 这个操作(方法),时间复杂度都是 O(n) 。 * 其他所有的操作(方法)运行在线性时间(粗略的讲)。 * 这个常数因子(10)相比于 LinkedList 实现类来说是比较低的。 * * *

Each ArrayList instance has a capacity. The capacity is * the size of the array used to store the elements in the list. It is always * at least as large as the list size. As elements are added to an ArrayList, * its capacity grows automatically. The details of the growth policy are not * specified beyond the fact that adding an element has constant amortized * time cost. * 每个 ArrayList 实例都有一个 capacity,这个 capacity 是被用来在列表中存储元素的数组大小。 * capacity 总是至少和列表的大小一样大。 * 当元素被添加到 ArrayList 中,列表的 capacity 也会自动增长。 * 除了添加一个元素有恒定均摊时间花费这个事实外,增长策略的细节没有做规定。 * * *

An application can increase the capacity of an ArrayList instance * before adding a large number of elements using the ensureCapacity * operation. This may reduce the amount of incremental reallocation. * 一个程序在添加大量的元素之前可以先增加 ArrayList 实例的 capacity, * 通过使用 ensureCapacity 方法可能会减少重新分配增量的次数。 * * *

Note that this implementation is not synchronized. * If multiple threads access an ArrayList instance concurrently, * and at least one of the threads modifies the list structurally, it * must be synchronized externally. (A structural modification is * any operation that adds or deletes one or more elements, or explicitly * resizes the backing array; merely setting the value of an element is not * a structural modification.) This is typically accomplished by * synchronizing on some object that naturally encapsulates the list. * 注意:这个实现类(ArrayList) 不是同步的。 * 如果多个线程并发访问一个 ArrayList 实例,并且至少有一个线程在结构上修改了列表,那么这个线程必须在 * (ArrayList 的)方法外部进行同步操作。(结构上的修改是添加删除一个或多个元素,或者是显示调整后备数组的 * 大小,仅仅是设置值(使用 set 方法)不算是结构上的修改。) * 这通常是通过在列表上自然封装的一些对象进行同步操作来完成的。 * * * If no such object exists, the list should be "wrapped" using the * {@link Collections#synchronizedList Collections.synchronizedList} * method. This is best done at creation time, to prevent accidental * unsynchronized access to the list:

 *   List list = Collections.synchronizedList(new ArrayList(...));
* 如果不存在此类对象,列表应该用 Collections.synchronizedList 静态方法包装。 * 这(使用包装列表)应该在创建的时候做,为了防止非同步的访问列表(示例代码如下): * List list = Collections.synchronizedList(new ArrayList(...)); * * *

* The iterators returned by this class"s {@link #iterator() iterator} and * {@link #listIterator(int) listIterator} methods are fail-fast: * if the list is structurally modified at any time after the iterator is * created, in any way except through the iterator"s own * {@link ListIterator#remove() remove} or * {@link ListIterator#add(Object) add} methods, the iterator will throw a * {@link ConcurrentModificationException}. Thus, in the face of * concurrent modification, the iterator fails quickly and cleanly, rather * than risking arbitrary, non-deterministic behavior at an undetermined * time in the future. * 这个类(ArrayList)的 iterator() 方法和 listIterator 方法返回出来的迭代器都是 fail-fast 的。 * 如果列表在迭代器创建之后在结构上被修改,除了调用迭代器的 remove 方法和 add 方法外,迭代器都会抛出 ConcurrentModificationException 异常。 * 因此,在并发修改情况下,迭代器快速干净地出 fail,而不是在未来某个不确定的时间,冒任意和不确定的风险。 * * *

Note that the fail-fast behavior of an iterator cannot be guaranteed * as it is, generally speaking, impossible to make any hard guarantees in the * presence of unsynchronized concurrent modification. Fail-fast iterators * throw {@code ConcurrentModificationException} on a best-effort basis. * Therefore, it would be wrong to write a program that depended on this * exception for its correctness: the fail-fast behavior of iterators * should be used only to detect bugs. * 注意:迭代器的 fail-fast 行为可能不像它保证的那样,一般来说,在非同步并发修改情况下,不可能去给出 * 任何硬性的保证。 * fail-fast 的迭代器会尽最大的努力抛出 ConcurrentModificationException 异常。 * 因此,写程序依赖这个异常为了正确性这点是错误的,迭代器的 fail-fast 行为仅仅被用来检查(程序中的) bug。 * * *

This class is a member of the * * Java Collections Framework. * 这个类(ArrayList)是 Java 集合框架的一员。 * * @author Josh Bloch * @author Neal Gafter * @see Collection * @see List * @see LinkedList * @see Vector * @since 1.2 * 编写者:Josh Bloch、Neal Gafter * 参看:Collection、List、LinkedList、Vector * 这个类自从 Java 1.2 就有了 */ public class ArrayList extends AbstractList implements List, 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. * (初始化容量为 0或者初始化集合为空)空实例共享此空数组(私有静态不可变变量)。 */ 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. * (没有指定初始化)默认(容量)大小(10)空实例共享此空数组(私有静态不可变变量),我们将它和 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 的容量是这个数组的长度。 * 当添加第一个元素时,任何带有 elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA 的空 ArrayList * 都将扩展为 DEFAULT_CAPACITY。 * * transient 关键字修饰,序列化时该值不会被带上 */ transient Object[] elementData; // non-private to simplify nested class access 非私有方便内部嵌套类访问 /** * The size of the ArrayList (the number of elements it contains). * ArrayList 的大小(ArrayList 包含的元素数量) * * @serial * 对象序列化时被带上 */ private int size; /** * Constructs an empty list with the specified initial capacity. * 使用指定初始化容量构造一个空列表 * * @param initialCapacity the initial capacity of the list * initialCapacity 参数为这个列表的初始化容量 * @throws IllegalArgumentException if the specified initial capacity * is negative * 抛出 IllegalArgumentException 异常,如果指定的初始化容量是负数 */ public ArrayList(int initialCapacity) { if (initialCapacity > 0) { // 创建指定初始化容量的 Object 数组 this.elementData = new Object[initialCapacity]; } else if (initialCapacity == 0) { // 使用有指定初始化值的共享空实例 this.elementData = EMPTY_ELEMENTDATA; } else { // 抛出 IllegalArgumentException 异常 throw new IllegalArgumentException("Illegal Capacity: "+ initialCapacity); } } /** * Constructs an empty list with an initial capacity of ten. * 使用初始化容量 10 来构造一个空列表 */ public ArrayList() { // 使用无指定初始化值的共享空实例,和上面的空实例区分开 this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA; } /** * Constructs a list containing the elements of the specified * collection, in the order they are returned by the collection"s * iterator. * 使用包含元素(元素个数可能为 0)的指定集合构造列表,并按照这个集合的迭代器返回元素顺序构造 * * @param c the collection whose elements are to be placed into this list * c 参数为要将它的元素放入列表的集合 * @throws NullPointerException if the specified collection is null * 抛出 NullPointerException(空指针)异常,如果指定的集合为 null */ public ArrayList(Collection c) { // 如果集合 c 为 null,则在调用 toArray 方法时会抛出空指针异常 elementData = c.toArray(); if ((size = elementData.length) != 0) { // c.toArray might (incorrectly) not return Object[] (see 6260652) // c.toArray 是具体的集合类中的方法,可能并不会正确的返回 Object 数组,所以这里要判断一下, // 如果不是 Object 数组,就通过 Arrays 工具类的 copyOf 方法转换成 Object 数组 if (elementData.getClass() != Object[].class) elementData = Arrays.copyOf(elementData, size, Object[].class); } else { // replace with empty array. // 使用有指定初始化值的共享空实例 this.elementData = EMPTY_ELEMENTDATA; } } /** * Trims the capacity of this ArrayList instance to be the * list"s current size. An application can use this operation to minimize * the storage of an ArrayList instance. * 调整 ArrayList 实例的 capacity 为列表当前的 size。 * 程序可以使用这个方法最小化 ArrayList 实例的存储(节省不需要的空间)。 */ public void trimToSize() { // 修改次数加 1 modCount++; // 在 size 小于数组的长度(数组中存在 null 引用)前提下 // 如果 size == 0 ,说明数组中都是 null 引用,就让 elementData 指向 EMPTY_ELEMENTDATA, // 否则,就拷贝 size 长度的 elementData 数组元素,再让 elementData 指向这个数组对象 if (size < elementData.length) { elementData = (size == 0) ? EMPTY_ELEMENTDATA : Arrays.copyOf(elementData, size); } } /** * Increases the capacity of this ArrayList instance, if * necessary, to ensure that it can hold at least the number of elements * specified by the minimum capacity argument. * 如果有需要,增加 ArrayList 实例的容量值,来确保它可以容纳至少 * 指定的最小容量(minCapacity)数量的元素。 * * @param minCapacity the desired minimum capacity * minCapacity 参数为列表所需的最小容量 */ public void ensureCapacity(int minCapacity) { // 如果 elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA(未指定初始化值的 ArrayList 实例),则 minExpand = 0 // 否则 minExpand = DEFAULT_CAPACITY(10) 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; // 如果 minCapacity > minExpand,一种情况是 minCapacity > 0,另一种情况是 minCapacity > 10 if (minCapacity > minExpand) { ensureExplicitCapacity(minCapacity); } } // 类内私有方法,对象无法直接方法,供内部其他方法使用 // 计算列表的容量 private static int calculateCapacity(Object[] elementData, int minCapacity) { // 如果 elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA(未指定初始化值的 ArrayList 实例),则返回 DEFAULT_CAPACITY(10) 和 minCapacity 数值最大的一个作为列表的容量 if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) { return Math.max(DEFAULT_CAPACITY, minCapacity); } // 否则(不是未指定初始化值得 ArrayList 实例),直接返回 minCapacity return minCapacity; } // 类内私有方法,对象无法直接方法,供内部其他方法使用 // 确保 ArrayList 内部容量充足 private void ensureCapacityInternal(int minCapacity) { ensureExplicitCapacity(calculateCapacity(elementData, minCapacity)); } // 类内私有方法,对象无法直接方法,供内部其他方法使用 // 确保已经有明确的容量 private void ensureExplicitCapacity(int minCapacity) { // 修改次数加 1 modCount++; // overflow-conscious code // 有溢出意识的代码 // 当 minCapacity 大于 elementData 数组长度时,再调用 grow 方法。 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.Max_VALUE - 8 * 为什么最大数组大小不是 Integer 最大值?因为一些虚拟机(VMs)在数组中会保留一些头消息,会占用一些空间 * 尝试分配比这个(规定最大)值更大的值可能会导致 OutOfMemoryError:请求的数组大小超过了虚拟机的限制 */ 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. * 确保 ArrayList 实例可以容纳至少指定的最小容量(minCapacity)数量的元素。 * * @param minCapacity the desired minimum capacity * minCapacity 参数为列表所需的最小容量 */ private void grow(int minCapacity) { // overflow-conscious code // 有溢出意识的代码 // oldCapacity 的值为 elementData 中数组长度值 int oldCapacity = elementData.length; // 使用位运算提高运算速度,newCapacity 是 oldCapacity 的 1.5 倍。 int newCapacity = oldCapacity + (oldCapacity >> 1); // 如果 oldCapacity 的 1.5 倍还比 minCapacity 小,那么 newCapacity = minCapacity if (newCapacity - minCapacity < 0) newCapacity = minCapacity; // 如果 oldCapacity 的 1.5 倍比 MAX_ARRAY_SIZE 大,那么调用 hugeCapacity 做点事情 if (newCapacity - MAX_ARRAY_SIZE > 0) newCapacity = hugeCapacity(minCapacity); // minCapacity is usually close to size, so this is a win: // minCapacity 的值通常接近于 size 的值,所以这就是个胜利(节省空间) // 最终 elementData 指向复制了 newCapacity 的新数组对象 elementData = Arrays.copyOf(elementData, newCapacity); } // 对于巨大的容量的做法 private static int hugeCapacity(int minCapacity) { // 如果 minCapacity < 0 就直接抛出 OutOfMemoryError if (minCapacity < 0) // overflow throw new OutOfMemoryError(); // 否则如果 minCapacity > MAX_ARRAY_SIZE,返回 Integer.MAX_VALUE,或者返回 MAX_ARRAY_SIZE 值 return (minCapacity > MAX_ARRAY_SIZE) ? Integer.MAX_VALUE : MAX_ARRAY_SIZE; } /** * Returns the number of elements in this list. * 返回列表中元素的数量 * @return the number of elements in this list * 返回值是列表中元素的数量 */ public int size() { return size; } /** * Returns true if this list contains no elements. * 如果列表中没有元素则返回 true * * @return true if this list contains no elements * 返回值为列表的 size 是否等于 0 */ public boolean isEmpty() { return size == 0; } /** * Returns true if this list contains the specified element. * More formally, returns true if and only if this list contains * at least one element e such that * (o==null ? e==null : o.equals(e)). * 如果列表包含指定的元素则返回 true, * 更正式的说是,当且仅当列表包含至少一个元素 e, * 就像这样 return (o == null ? e == null : o.equals(e)) * 如果测试对象 o 为 null,那么这一个元素 e 指向 null,返回 true * 否则就用 o 调用 equals 方法,判断 o 和 e 是否相等来决定返回值 * * @param o element whose presence in this list is to be tested * o 参数为在这个列表中被测试的元素 * @return true if this list contains the specified element * 返回值为 o 在列表中的位置是否大于 0 */ public boolean contains(Object o) { return indexOf(o) >= 0; } /** * Returns the index of the first occurrence of the specified element * in this list, or -1 if this list does not contain the element. * More formally, returns the lowest index i such that * (o==null ? get(i)==null : o.equals(get(i))), * or -1 if there is no such index. * 返回列表中第一次出现指定元素的索引(下标),如果列表中不存在这个(指定)元素就返回 -1 * 更正式的说是,返回最小的索引, * 就像这样 (o == null ? get(i) == null : o.equals(get(i))) * 或者(列表中)没有该元素的索引就返回 -1 * 这里方法注释是源码注释不规范(不是我翻译时漏了),没有参数和返回值的注释, * 不知道是编写这个类中哪个大佬的锅,txtx */ public int indexOf(Object o) { // 判断 o 是不是指向 null if (o == null) { // 如果 o 指向 null,正序遍历元素列表(注意这里用 size,不用 capacity),如果找到就返回索引值 for (int i = 0; i < size; i++) if (elementData[i]==null) return i; } else { // 如果 o 不指向 null,正序遍历元素列表,使用元素的 equals 方法判断元素值,如果找到就返回索引值 for (int i = 0; i < size; i++) if (o.equals(elementData[i])) return i; } // 找不到返回 -1 return -1; } /** * Returns the index of the last occurrence of the specified element * in this list, or -1 if this list does not contain the element. * More formally, returns the highest index i such that * (o==null ? get(i)==null : o.equals(get(i))), * or -1 if there is no such index. * 返回列表中最后一次出现指定元素的索引(下标),如果列表中不存在这个(指定)元素就返回 -1 * 更正式的说是,返回最小的索引, * 就像这样 (o == null ? get(i) == null : o.equals(get(i))) * 或者(列表中)没有该元素的索引就返回 -1 */ public int lastIndexOf(Object o) { // 判断 o 是不是指向 null if (o == null) { // 如果 o 指向 null,倒序遍历元素列表(注意这里用 size,不用 capacity),如果找到就返回索引值 for (int i = size-1; i >= 0; i--) if (elementData[i]==null) return i; } else { // 如果 o 不指向 null,正序遍历元素列表,使用元素的 equals 方法判断元素值,如果找到就返回索引值 for (int i = size-1; i >= 0; i--) if (o.equals(elementData[i])) return i; } // 找不到返回 -1 return -1; } /** * Returns a shallow copy of this ArrayList instance. (The * elements themselves are not copied.) * 返回 ArrayList 实例的浅拷贝(元素本身没有拷贝,只是把数组中的对象引用拷贝了一遍) * * @return a clone of this ArrayList instance * 返回值是 ArrayList 实例的克隆 */ public Object clone() { try { // 只是复制了 ArrayList 数组对象引用(栈中),没有拷贝具体的对象(堆中) ArrayList v = (ArrayList) super.clone(); // elementData 复制和 modCount 值复制 v.elementData = Arrays.copyOf(elementData, size); v.modCount = 0; return v; } catch (CloneNotSupportedException e) { // this shouldn"t happen, since we are Cloneable // 这不应该发生,因为我们已经声明了 Cloneable throw new InternalError(e); } } /** * Returns an array containing all of the elements in this list * in proper sequence (from first to last element). * 以适当的顺序(从第一个到最后一个元素)返回一个包含列表中所有元素的数组 * *

The returned array will be "safe" in that no references to it are * maintained by this list. (In other words, this method must allocate * a new array). The caller is thus free to modify the returned array. * 这个返回的数组是安全的,列表中没有保留对数组元素值的引用(换句话说,这个方法必须分配一个新的数组) * 调用者因此可以自由修改返回的数组(对列表中的值不会有影响,反过来,列表中的值修改也不会影响数组中的值) * *

This method acts as bridge between array-based and collection-based * APIs. * 这个方法充当基于数组和基于集合API的桥梁(集合与数组的转换) * * @return an array containing all of the elements in this list in * proper sequence * 返回值为以适当的顺序包含列表中所有元素的数组 */ public Object[] toArray() { // copyOf 方法最终调用的是 System.arraycopy 静态方法,并且是个本地方法,无法查看源代码 return Arrays.copyOf(elementData, size); } /** * Returns an array containing all of the elements in this list in proper * sequence (from first to last element); the runtime type of the returned * array is that of the specified array. If the list fits in the * specified array, it is returned therein. Otherwise, a new array is * allocated with the runtime type of the specified array and the size of * this list. * 以适当的顺序(从第一个到最后一个元素)返回一个包含列表中所有元素的数组; * 返回数组的运行类型是指定数组的类型。 * 如果列表适合指定的数组,则返回到指定数组中(指定数组长度和列表 size 大小相等) * 否则一个以指定数组的类型为运行类型,大小为列表 size 的新数组将被分配 * *

If the list fits in the specified array with room to spare * (i.e., the array has more elements than the list), the element in * the array immediately following the end of the collection is set to * null. (This is useful in determining the length of the * list only if the caller knows that the list does not contain * any null elements.) * 如果列表适合指定的数组并且还有剩余空间(即指定数组比列表有更多的元素),在数组中紧跟集合末尾的元素被设置为 null。(仅当调用者知道列表中不包含任何 null 元素,在决定列表长度时才是有用的) * * @param a the array into which the elements of the list are to * be stored, if it is big enough; otherwise, a new array of the * same runtime type is allocated for this purpose. * a 参数是一个用来存储列表元素的数组,前提是这个数组足够大;否则,一个以转换目的和指定数组相同类型的数组将会被分配 * @return an array containing the elements of the list * 返回值为包含列表元素的数组 * @throws ArrayStoreException if the runtime type of the specified array * is not a supertype of the runtime type of every element in * this list * 抛出 ArrayStoreException 异常,如果指定数组的类型不是列表元素类型的超类型 * @throws NullPointerException if the specified array is null * 抛出 NullPointerException 异常,如果指定的数组是 null */ @SuppressWarnings("unchecked") public T[] toArray(T[] a) { // 如果指定的数组长度小于 size,返回一个以列表元素填充的新数组 if (a.length < size) // Make a new array of a"s runtime type, but my contents: return (T[]) Arrays.copyOf(elementData, size, a.getClass()); // 数组拷贝,System.arraycopy 方法为本地方法 System.arraycopy(elementData, 0, a, 0, size); // 如果指定数组长度大于 size,超过列表 size 的部分赋值为 null if (a.length > size) a[size] = null; // 再将填充后指定的数组返回 return a; } // Positional Access Operations // 按位置访问操作(方法) @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 * index 参数为要返回元素的下标 * @return the element at the specified position in this list * 返回值为列表中指定位置的元素 * @throws IndexOutOfBoundsException {@inheritDoc} * 抛出 IndexOutOfBoundsException 异常 */ public E get(int index) { // 边界检查 rangeCheck(index); return elementData(index); } /** * Replaces the element at the specified position in this list with * the specified element. * 用指定元素替换列表中指定位置的元素值 * * @param index index of the element to replace * index 参数为要替换的元素的下标 * @param element element to be stored at the specified position * element 参数为要存储到指定位置的元素值 * @return the element previously at the specified position * 返回值为先前指定位置的旧元素值 * @throws IndexOutOfBoundsException {@inheritDoc} * 抛出 IndexOutOfBoundsException 异常 */ public E set(int index, E element) { // 边界检查 rangeCheck(index); // 保存旧值 E oldValue = elementData(index); // 替换成新值 elementData[index] = element; // 返回旧值 return oldValue; } /** * Appends the specified element to the end of this list. * 添加指定元素到列表末尾 * * @param e element to be appended to this list * e 参数为要添加到列表的元素 * @return true (as specified by {@link Collection#add}) * 返回值为 true(当被指定为集合时) */ public boolean add(E e) { // 确保在 ArrayList 实例的 size 基础上加 1,容量仍然充足,扩充是以 elementData 数组长度的 1.5 倍扩的 ensureCapacityInternal(size + 1); // Increments modCount!! // 这里一行代码实现了两步,一步是 size 加 1,另一步是将 e 添加到 elementData 末尾 elementData[size++] = e; return true; } /** * Inserts the specified element at the specified position in this * list. Shifts the element currently at that position (if any) and * any subsequent elements to the right (adds one to their indices). * 插入指定的值到列表指定的位置。 * 将当前位置的元素(如果有的话)和任何后续的元素向右移动(将它们的索引加 1) * * @param index index at which the specified element is to be inserted * index 参数为要被插入的指定元素的索引 * @param element element to be inserted * element 参数为要插入的元素 * @throws IndexOutOfBoundsException {@inheritDoc} * 抛出 IndexOutOfBoundsException 异常 */ public void add(int index, E element) { // add 方法的边界检查 rangeCheckForAdd(index); // 确保在 ArrayList 实例的 size 基础上加 1,容量仍然充足 ensureCapacityInternal(size + 1); // Increments modCount!! // 元素向后移动是通过 System.arraycopy 方法实现的 System.arraycopy(elementData, index, elementData, index + 1, size - index); // 数组指定位置赋值 elementData[index] = element; // ArrayList 的 size 要加 1 size++; } /** * Removes the element at the specified position in this list. * Shifts any subsequent elements to the left (subtracts one from their * indices). * 移除列表指定位置的元素,将后续的元素向左移动(将它们的减 1) * * @param index the index of the element to be removed * @return the element that was removed from the list * @throws IndexOutOfBoundsException {@inheritDoc} */ public E remove(int index) { // 边界检查 rangeCheck(index); // 修改次数加 1 modCount++; // 保存旧值 E oldValue = elementData(index); // 计算要移动的元素个数 int numMoved = size - index - 1; if (numMoved > 0) // 使用 System.arraycopy 方法实现元素向左移动 System.arraycopy(elementData, index+1, elementData, index, numMoved); // 一行代码,两步操作,一步是将 size 减 1,另一步是将最后一个元素指向 null,让垃圾回收器清理没有引用的对象 elementData[--size] = null; // clear to let GC do its work // 返回旧值 return oldValue; } /** * Removes the first occurrence of the specified element from this list, * if it is present. If the list does not contain the element, it is * unchanged. More formally, removes the element with the lowest index * i such that * (o==null ? get(i)==null : o.equals(get(i))) * (if such an element exists). Returns true if this list * contained the specified element (or equivalently, if this list * changed as a result of the call). * 移除列表中第一次出现的指定元素,前提是这个元素值存在。 * 如果列表不包含这个元素,列表不会改变。 * * * @param o element to be removed from this list, if present * @return true if this list contained the specified element */ public boolean remove(Object o) { // 如果 o 指向 null,遍历 elementData 数组,如果找到了指定元素就删除并返回 true if (o == null) { for (int index = 0; index < size; index++) if (elementData[index] == null) { fastRemove(index); return true; } } else { // 否则,遍历 elementData 数组,使用 equals 方法判断相等,如果找到了指定元素就删除并返回 true for (int index = 0; index < size; index++) if (o.equals(elementData[index])) { fastRemove(index); return true; } } // 没有找到,返回 false return false; } /* * Private remove method that skips bounds checking and does not * return the value removed. * 私有的删除方法,跳过了边界检查并且不返回删除的值 */ private void fastRemove(int index) { // 修改次数加 1 modCount++; // 计算要移动的元素的个数 int numMoved = size - index - 1; if (numMoved > 0) // 使用 System.arraycopy 方法实现元素向左移动 System.arraycopy(elementData, index+1, elementData, index, numMoved); // 一行代码,两步操作,一步是将 size 减 1,另一步是将最后一个元素指向 null,让垃圾回收器清理没有引用的对象 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() { // 修改次数加 1 modCount++; // clear to let GC do its work // elementData 数组中的引用都置为 null,让垃圾回收器清除没有引用的对象 for (int i = 0; i < size; i++) elementData[i] = null; size = 0; }

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/75869.html

相关文章

  • Java相关

    摘要:本文是作者自己对中线程的状态线程间协作相关使用的理解与总结,不对之处,望指出,共勉。当中的的数目而不是已占用的位置数大于集合番一文通版集合番一文通版垃圾回收机制讲得很透彻,深入浅出。 一小时搞明白自定义注解 Annotation(注解)就是 Java 提供了一种元程序中的元素关联任何信息和着任何元数据(metadata)的途径和方法。Annotion(注解) 是一个接口,程序可以通过...

    wangtdgoodluck 评论0 收藏0
  • java源码

    摘要:集合源码解析回归基础,集合源码解析系列,持续更新和源码分析与是两个常用的操作字符串的类。这里我们从源码看下不同状态都是怎么处理的。 Java 集合深入理解:ArrayList 回归基础,Java 集合深入理解系列,持续更新~ JVM 源码分析之 System.currentTimeMillis 及 nanoTime 原理详解 JVM 源码分析之 System.currentTimeMi...

    Freeman 评论0 收藏0
  • net - 收藏集 - 掘金

    摘要:再者,现在互联网的面试中上点的都会涉及一下或者的问题个高级多线程面试题及回答后端掘金在任何面试当中多线程和并发方面的问题都是必不可少的一部分。假如源码分析之掘金概念是中集合的一种实现。 攻破 JAVA NIO 技术壁垒 - 后端 - 掘金现在使用NIO的场景越来越多,很多网上的技术框架或多或少的使用NIO技术,譬如Tomcat,Jetty。学习和掌握NIO技术已经不是一个JAVA攻城狮...

    岳光 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<