当前位置:   article > 正文

Java数据存储之---ArrayList_arraylist里对象的值

arraylist里对象的值

官方文档描述

可调整大小的数组实现了List的接口。实现所有可选列表操作,并允许所有元素包括null。除了实现List接口, 这个类提供了操作数组大小的方法在内部用于存储列表。(这个类大致相当于
 Vector,除了它是不同步的。)这些操作size,isEmpty,get,set,iterator,listIterator操作在固定的常数时间内运行,add操作在摊销的常数时间内运行,也就是说添加 n 个元素需要 O(n) 时间。所有其他操作以线性时间运行(粗略地说),与 LinkedList实现相比,常数因子较低。每个 ArrayList 实例都有一个容量,容量是用于存储列表中元素的数组的大小。它总是至少与列表大小一样大。随着元素被添加到 ArrayList,它的容量会自动增长。除了添加一个元素具有恒定的摊销时间成本这一事实之外,没有指定增长策略的细节。应用程序可以在添加大量元素之前使用 ensureCapacity 增加 ArrayList实例的容量。这可以减少增量重新分配的数量。请注意,此实现不是同步的。

如果多个线程同时访问一个 ArrayList实例, 并且至少有一个线程在结构上修改了列表,它
 必须在外部同步。 (结构修改是添加或删除一个或多个元素,或显式调整后备数组大小的任何操作;仅设置元素的值不是结构修改。)这通常通过同步一些自然封装的对象来完成列表。

如果不存在这样的对象,则应使用

{@link Collections#synchronizedList Collections.synchronizedList}

方法。这最好在创建时完成,以防止意外对列表的非同步访问:

 List list = Collections.synchronizedList(new ArrayList(...));

此类的 {@link #iterator() 迭代器} 返回的迭代器和 {@link #listIterator(int) listIterator} 方法是快速失败。如果列表在迭代器之后的任何时间都在结构上被修改,以任何方式,除了通过迭代器自己的{@link ListIterator#remove() remove} {@link ListIterator#add(Object) add} 方法,迭代器将抛出 {@link ConcurrentModificationException} 因此,面对并发修改,迭代器快速而干净地失败,而不是在未来不确定的时间冒任意的、非确定性的行为。

请注意,不能保证迭代器的快速失败行为,因为一般来说,在存在不同步的并发修改的情况下,不可能做出任何硬保证。 快速失败的迭代器会尽最大努力抛出 {@code ConcurrentModificationException}。因此,编写一个依赖于这个异常的正确性的程序是错误的:迭代器的快速失败行为应该只用于检测错误。

类初始化

  1. /**
  2. * 默认初始容量
  3. */
  4. private static final int DEFAULT_CAPACITY = 10;
  5. /**
  6. * 用于空实例的共享空数组实例
  7. */
  8. private static final Object[] EMPTY_ELEMENTDATA = {};
  9. /**
  10. * 用于默认大小的空实例的共享空数组实例
  11. * 将其与 EMPTY_ELEMENTDATA 区分开来,以了解添加第一个元素时要扩充多少
  12. */
  13. private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
  14. /**
  15. * 存储 ArrayList元素的数组缓冲区。
  16. * ArrayList的容量就是这个数组缓冲区的长度。
  17. * 任何带有elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA的空ArrayList添加第一个元素时将扩展 为 DEFAULT_CAPACITY
  18. */
  19. // Android-note: 也可以从 java.util.Collections 访问
  20. transient Object[] elementData; // 非私有以简化嵌套类访问
  21. /**
  22. * ArrayList 的大小(它包含的元素数量)。
  23. */
  24. private int size;
  25. /**
  26. * 构造一个具有指定初始容量的空列表。
  27. *
  28. * @param initialCapacity 列表的初始容量
  29. * @throws IllegalArgumentException 如果指定的初始容量为负
  30. */
  31. public ArrayList(int initialCapacity) {
  32. if (initialCapacity > 0) {
  33. this.elementData = new Object[initialCapacity];
  34. } else if (initialCapacity == 0) {
  35. this.elementData = EMPTY_ELEMENTDATA;
  36. } else {
  37. throw new IllegalArgumentException("Illegal Capacity: "+ initialCapacity);
  38. }
  39. }
  40. /**
  41. * 构造一个初始容量为 10 的空列表。
  42. */
  43. public ArrayList() {
  44. this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
  45. }
  46. /**
  47. * 按照集合的迭代器返回的顺序构造一个包含指定集合元素的列表。
  48. *
  49. * @param c 将其元素放入此列表的集合
  50. * @throws NullPointerException 如果指定的集合为空
  51. */
  52. public ArrayList(Collection<? extends E> c) {
  53. elementData = c.toArray();
  54. if ((size = elementData.length) != 0) {
  55. // c.toArray might (incorrectly) not return Object[] (see 6260652)
  56. if (elementData.getClass() != Object[].class)
  57. elementData = Arrays.copyOf(elementData, size, Object[].class);
  58. } else {
  59. // replace with empty array.
  60. this.elementData = EMPTY_ELEMENTDATA;
  61. }
  62. }

容量相关

  1. /**
  2. * 如有必要,增加此 <tt>ArrayList</tt> 实例的容量
  3. * 以确保它至少可以容纳最小容量参数指定的元素数量
  4. *
  5. * @param minCapacity 所需的最小容量
  6. */
  7. public void ensureCapacity(int minCapacity) {
  8. int minExpand = (elementData != DEFAULTCAPACITY_EMPTY_ELEMENTD
  9. // 如果不是默认元素表,则为任何大小
  10. ? 0
  11. // 大于默认空表的默认值, 它应该是默认大小
  12. : DEFAULT_CAPACITY;
  13. if (minCapacity > minExpand) {
  14. ensureExplicitCapacity(minCapacity);
  15. }
  16. }
  17. private void ensureExplicitCapacity(int minCapacity) {
  18. modCount++;
  19. // 考虑到溢出的情况
  20. if (minCapacity - elementData.length > 0)
  21. grow(minCapacity);
  22. }
  23. /**
  24. * 要分配的数组的最大大小
  25. * 一些 VM 在数组中保留一些标题字
  26. * 尝试分配更大的数组可能会导致
  27. * OutOfMemoryError:请求的数组大小超过 VM 限制
  28. */
  29. private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
  30. /**
  31. * 增加容量以确保它至少可以容纳最小容量参数指定的元素数量
  32. *
  33. * @param minCapacity 所需的最小容量
  34. */
  35. private void grow(int minCapacity) {
  36. // overflow-conscious code
  37. int oldCapacity = elementData.length;
  38. int newCapacity = oldCapacity + (oldCapacity >> 1);
  39. if (newCapacity - minCapacity < 0)
  40. newCapacity = minCapacity;
  41. if (newCapacity - MAX_ARRAY_SIZE > 0)
  42. newCapacity = hugeCapacity(minCapacity);
  43. // minCapacity 通常接近 size
  44. elementData = Arrays.copyOf(elementData, newCapacity);
  45. }
  46. private static int hugeCapacity(int minCapacity) {
  47. if (minCapacity < 0) //溢出
  48. throw new OutOfMemoryError();
  49. return (minCapacity > MAX_ARRAY_SIZE) ?
  50. Integer.MAX_VALUE :
  51. MAX_ARRAY_SIZE;
  52. }

重要方法

  1. /**
  2. * 返回此列表中的元素个数
  3. */
  4. public int size() {
  5. return size;
  6. }
  7. /**
  8. * 根据size判断列表是否为空
  9. */
  10. public boolean isEmpty() {
  11. return size == 0;
  12. }
  13. /**
  14. * p判断是否包含某一个元素,使用indexOf方法完成,如果返回-1表示没有包含该元素
  15. */
  16. public boolean contains(Object o) {
  17. return indexOf(o) >= 0;
  18. }
  19. /**
  20. * 返回此列表中指定元素第一次出现的索引,如果此列表不包含该元素,则返回 -1
  21. */
  22. public int indexOf(Object o) {
  23. if (o == null) {//找空元素的位置
  24. for (int i = 0; i < size; i++)
  25. if (elementData[i]==null)
  26. return i;
  27. } else {
  28. for (int i = 0; i < size; i++)
  29. if (o.equals(elementData[i]))//遍历缓存数组elementData,找到相等的元素
  30. return i;
  31. }
  32. return -1;
  33. }
  34. /**
  35. * 返回最后一个指定的元素
  36. */
  37. public int lastIndexOf(Object o) {//遍历从缓存数组elementData的尾部开始
  38. if (o == null) {
  39. for (int i = size-1; i >= 0; i--)
  40. if (elementData[i]==null)
  41. return i;
  42. } else {
  43. for (int i = size-1; i >= 0; i--)
  44. if (o.equals(elementData[i]))
  45. return i;
  46. }
  47. return -1;
  48. }
  49. /**
  50. * 返回ArrayList 实例的浅表副本
  51. *(元素本身不会被复制)
  52. */
  53. public Object clone() {
  54. try {
  55. ArrayList<?> v = (ArrayList<?>) super.clone();
  56. v.elementData = Arrays.copyOf(elementData, size);
  57. v.modCount = 0;
  58. return v;
  59. } catch (CloneNotSupportedException e) {
  60. // this shouldn't happen, since we are Cloneable
  61. throw new InternalError(e);
  62. }
  63. }
  64. /**
  65. * 以正确的顺序(从第一个元素到最后一个元素)返回包含此列表中所有元素的数组
  66. * 返回的数组将是“安全的”,因为没有对它的引用由这个列表维护
  67. * (换句话说,这个方法必须分配一个新数组)
  68. * 因此,调用者可以自由修改返回的数组
  69. * 此方法充当基于数组的 API 和基于集合的 API 之间的桥梁。
  70. */
  71. public Object[] toArray() {
  72. return Arrays.copyOf(elementData, size);
  73. }
  74. /**
  75. * 以正确的顺序(从第一个元素到最后一个元素)返回一个包含此列表中所有元素的数组
  76. * 返回数组的运行时类型是指定数组的运行时类型
  77. * 如果列表适合指定的数组,则在其中返回
  78. * 否则,将使用指定数组的运行时类型和此列表的大小分配一个新数组
  79. *
  80. * 如果列表适合指定的数组并有剩余空间(即数组的元素比列表多)
  81. * 则数组中紧跟集合末尾的元素设置为null
  82. *(如果调用者知道列表不包含任何空元素,这对于确定列表的长度only很有用。)
  83. *
  84. * @param a 存储列表元素的数组(如果它足够大);否则,将为此目的分配相同运行时类型的新数组。
  85. * @return 包含列表元素的数组
  86. * @throws ArrayStoreException 如果指定数组的运行时类型不是此列表中每个元素的运行时类型的超类型
  87. * @throws NullPointerException 如果指定的数组为空
  88. */
  89. @SuppressWarnings("unchecked")
  90. public <T> T[] toArray(T[] a) {//泛型
  91. if (a.length < size)
  92. // Make a new array of a's runtime type, but my contents:
  93. return (T[]) Arrays.copyOf(elementData, size, a.getClass());
  94. System.arraycopy(elementData, 0, a, 0, size);
  95. if (a.length > size)
  96. a[size] = null;
  97. return a;
  98. }
  99. /**
  100. * 返回此列表中指定位置的元素。
  101. *
  102. * @param index 要返回的元素的索引
  103. * @return 此列表中指定位置的元素
  104. * @throws IndexOutOfBoundsException {@inheritDoc}
  105. */
  106. public E get(int index) {
  107. if (index >= size)
  108. throw new IndexOutOfBoundsException(outOfBoundsMsg(index));//索引超过列表长度
  109. return (E) elementData[index];
  110. }
  111. /**
  112. * 将此列表中指定位置的元素替换为指定元素
  113. *
  114. * @param index 要替换的元素的索引
  115. * @param element 要存储在指定位置的元素
  116. * @return 先前在指定位置的元素
  117. * @throws IndexOutOfBoundsException {@inheritDoc}
  118. */
  119. public E set(int index, E element) {
  120. if (index >= size)
  121. throw new IndexOutOfBoundsException(outOfBoundsMsg(index));//索引超过列表长度
  122. E oldValue = (E) elementData[index];
  123. elementData[index] = element;
  124. return oldValue;
  125. }
  126. /**
  127. * 将指定元素附加到此列表的末尾。
  128. *
  129. * @param e 要附加到此列表的元素
  130. * @return true (如指定的 {@link Collection#add})
  131. */
  132. public boolean add(E e) {
  133. ensureCapacityInternal(size + 1); // 增加 modCount!!
  134. elementData[size++] = e;
  135. return true;
  136. }
  137. /**
  138. * 在此列表中的指定位置插入指定元素
  139. * 将当前位于该位置的元素(如果有)和任何后续元素向右移动(将其索引加一)
  140. *
  141. * @param index 要插入指定元素的索引
  142. * @param element 要插入的元素
  143. * @throws IndexOutOfBoundsException {@inheritDoc}
  144. */
  145. public void add(int index, E element) {
  146. if (index > size || index < 0)
  147. throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
  148. ensureCapacityInternal(size + 1); // 增加 modCount!!
  149. System.arraycopy(elementData, index, elementData, index + 1,
  150. size - index);
  151. elementData[index] = element;
  152. size++;
  153. }
  154. /**
  155. * 移除此列表中指定位置的元素
  156. * 将任何后续元素向左移动(从它们的索引中减去 1)
  157. *
  158. * @param index 要删除的元素的索引
  159. * @return 从列表中删除的元素
  160. * @throws IndexOutOfBoundsException {@inheritDoc}
  161. */
  162. public E remove(int index) {
  163. if (index >= size)
  164. throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
  165. modCount++;
  166. E oldValue = (E) elementData[index];
  167. int numMoved = size - index - 1;
  168. if (numMoved > 0)
  169. System.arraycopy(elementData, index+1, elementData, index,
  170. numMoved);
  171. elementData[--size] = null; // 置空,则会被内存(内存管理GC)回收
  172. return oldValue;
  173. }
  174. /**
  175. * 从此列表中删除第一次出现的指定元素(如果存在)
  176. * 如果列表不包含该元素,则它是不变的。
  177. * 更正式地说,删除具有最低索引 i 的元素
  178. * 使得 (o==null&nbsp;&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))(如果存在这样的元素)
  179. * 如果此列表包含指定元素(或等效地,如果此列表因调用而更改),则返回true。
  180. *
  181. * @param o 要从此列表中删除的元素(如果存在)
  182. * @return true如果此列表包含指定的元素
  183. */
  184. public boolean remove(Object o) {
  185. if (o == null) {
  186. for (int index = 0; index < size; index++)
  187. if (elementData[index] == null) {
  188. fastRemove(index);
  189. return true;
  190. }
  191. } else {
  192. for (int index = 0; index < size; index++)
  193. if (o.equals(elementData[index])) {
  194. fastRemove(index);
  195. return true;
  196. }
  197. }
  198. return false;
  199. }
  200. /*
  201. * 跳过边界检查且不返回已删除值的私有删除方法
  202. */
  203. private void fastRemove(int index) {
  204. modCount++;
  205. int numMoved = size - index - 1;
  206. if (numMoved > 0)
  207. System.arraycopy(elementData, index+1, elementData, index,
  208. numMoved);
  209. elementData[--size] = null; // 置空,则会被内存(内存管理GC)回收
  210. }
  211. /**
  212. * 从此列表中删除所有元素。 此调用返回后,列表将为空
  213. */
  214. public void clear() {
  215. modCount++;
  216. // clear to let GC do its work
  217. for (int i = 0; i < size; i++)
  218. elementData[i] = null;
  219. size = 0;
  220. }
  221. /**
  222. * 按照指定集合的迭代器返回的顺序,将指定集合中的所有元素附加到此列表的末尾
  223. * 如果在操作正在进行时修改了指定的集合,则此操作的行为是未定义的
  224. *(这意味着如果指定的集合是这个列表,并且这个列表是非空的,那么这个调用的行为是未定义的。)
  225. *
  226. * @param c 包含要添加到此列表的元素的集合
  227. * @return true如果此列表因调用而更改
  228. * @throws NullPointerException 如果指定的集合为空
  229. */
  230. public boolean addAll(Collection<? extends E> c) {
  231. Object[] a = c.toArray();
  232. int numNew = a.length;
  233. ensureCapacityInternal(size + numNew);
  234. System.arraycopy(a, 0, elementData, size, numNew);
  235. size += numNew;
  236. return numNew != 0;
  237. }
  238. /**
  239. * 将指定集合中的所有元素插入此列表,从指定位置开始
  240. * 将当前位于该位置的元素(如果有)和任何后续元素向右移动(增加它们的索引)
  241. * 新元素将按照指定集合的迭代器返回的顺序出现在列表中。
  242. *
  243. * @param index 插入指定集合中第一个元素的索引
  244. * @param c 包含要添加到此列表的元素的集合
  245. * @return <tt>true</tt> 如果此列表因调用而更改
  246. * @throws IndexOutOfBoundsException {@inheritDoc}
  247. * @throws NullPointerException 如果指定的集合为空
  248. */
  249. public boolean addAll(int index, Collection<? extends E> c) {
  250. if (index > size || index < 0)
  251. throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
  252. Object[] a = c.toArray();
  253. int numNew = a.length;
  254. ensureCapacityInternal(size + numNew);
  255. int numMoved = size - index;
  256. if (numMoved > 0)
  257. System.arraycopy(elementData, index, elementData, index + numNew,
  258. numMoved);
  259. System.arraycopy(a, 0, elementData, index, numNew);
  260. size += numNew;
  261. return numNew != 0;
  262. }

copyOf(在JDK中)

  1. /**
  2. * 复制指定的数组,用空值截断或填充(如有必要),使副本具有指定的长度
  3. * 对于在原始数组和副本中都有效的所有索引,这两个数组将包含相同的值
  4. * 对于在副本中有效但在原始数组中无效的任何索引,副本将包含null
  5. * 当且仅当指定长度大于原始数组的长度时,此类索引才会存在
  6. * 生成的数组 属于newType类。
  7. *
  8. * @param <U> 原始数组中对象的类
  9. * @param <T> 返回数组中对象的类
  10. * @param original 要复制的数组
  11. * @param newLength 要返回的副本的长度
  12. * @param newType 要返回的副本的类别
  13. * @return 原始数组的副本,被截断或用空值填充以获得指定的长度
  14. * @throws NegativeArraySizeException 如果newLength为负
  15. * @throws NullPointerException 如果original为空
  16. * @throws ArrayStoreException 如果从original复制的元素不是可以存储在类newType的数组中的运行时类型
  17. */
  18. public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) {
  19. @SuppressWarnings("unchecked")
  20. T[] copy = ((Object)newType == (Object)Object[].class)
  21. ? (T[]) new Object[newLength]
  22. : (T[]) Array.newInstance(newType.getComponentType(), newLength);
  23. System.arraycopy(original, 0, copy, 0,
  24. Math.min(original.length, newLength));
  25. return copy;
  26. }

本文内容由网友自发贡献,转载请注明出处:https://www.wpsshop.cn/w/Gausst松鼠会/article/detail/231666
推荐阅读
相关标签
  

闽ICP备14008679号