1. package com.yum.day07;
    2. import java.util.*;
    3. public class ArrayList<E> extends AbstractList<E>
    4. implements List<E>, RandomAccess, Cloneable, java.io.Serializable {
    5. private static final long serialVersionUID = 8683452581122892189L;
    6. //默认容量
    7. private static final int DEFAULT_CAPACITY = 10;
    8. //空对象
    9. private static final Object[] EMPTY_ELEMENTDATA = {};
    10. // 一个空对象,如果使用默认构造函数创建,则默认对象内容默认是该值
    11. private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
    12. // 当前数据对象存放地方,当前对象不参与序列化
    13. transient Object[] elementData;
    14. // 当前数组长度
    15. private int size;
    16. /**
    17. * 通过大小进行构造
    18. */
    19. public ArrayList(int initialCapacity) {
    20. if (initialCapacity > 0) {
    21. this.elementData = new Object[initialCapacity];
    22. } else if (initialCapacity == 0) {
    23. this.elementData = EMPTY_ELEMENTDATA;
    24. } else {
    25. throw new IllegalArgumentException("Illegal Capacity: " +
    26. initialCapacity);
    27. }
    28. }
    29. /**
    30. * 构造一个空列表。
    31. */
    32. public ArrayList() {
    33. this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
    34. }
    35. /**
    36. * 带collection的构造器
    37. */
    38. public ArrayList(Collection<? extends E> c) {
    39. //浅复制
    40. elementData = c.toArray();
    41. if ((size = elementData.length) != 0) {
    42. if (elementData.getClass() != Object[].class)
    43. //深复制
    44. elementData = Arrays.copyOf(elementData, size, Object[].class);
    45. } else {
    46. //返回一个空的
    47. this.elementData = EMPTY_ELEMENTDATA;
    48. }
    49. }
    50. //将空余空间去除
    51. public void trimToSize() {
    52. modCount++;
    53. if (size < elementData.length) {
    54. elementData = (size == 0)
    55. ? EMPTY_ELEMENTDATA
    56. : Arrays.copyOf(elementData, size);
    57. }
    58. }
    59. public void ensureCapacity(int minCapacity) {
    60. int minExpand = (elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA)
    61. // any size if not default element table
    62. ? 0
    63. // larger than default for default empty table. It's already
    64. // supposed to be at default size.
    65. : DEFAULT_CAPACITY;
    66. if (minCapacity > minExpand) {
    67. ensureExplicitCapacity(minCapacity);
    68. }
    69. }
    70. //确保数组已使用长度(size)加1之后足够存下 下一个数据
    71. private void ensureCapacityInternal(int minCapacity) {
    72. ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
    73. }
    74. //计算容量
    75. private static int calculateCapacity(Object[] elementData, int minCapacity) {
    76. if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
    77. return Math.max(DEFAULT_CAPACITY, minCapacity);
    78. }
    79. return minCapacity;
    80. }
    81. //将修改次数(modCount)自增1,判断是否需要扩充数组长度,判断条件就是用当前所需的数组最小长度与数组的长度对比,如果大于0,则增长数组长度。
    82. private void ensureExplicitCapacity(int minCapacity) {
    83. modCount++;
    84. // overflow-conscious code
    85. if (minCapacity - elementData.length > 0)
    86. grow(minCapacity);
    87. }
    88. private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
    89. /**
    90. * 如果当前的数组已使用空间(size)加1之后 大于数组长度,则增大数组容量,扩大为原来的1.5倍。
    91. */
    92. private void grow(int minCapacity) {
    93. // overflow-conscious code
    94. int oldCapacity = elementData.length;
    95. int newCapacity = oldCapacity + (oldCapacity >> 1);
    96. if (newCapacity - minCapacity < 0)
    97. newCapacity = minCapacity;
    98. if (newCapacity - MAX_ARRAY_SIZE > 0)
    99. newCapacity = hugeCapacity(minCapacity);
    100. elementData = Arrays.copyOf(elementData, newCapacity);
    101. }
    102. private static int hugeCapacity(int minCapacity) {
    103. if (minCapacity < 0) // overflow
    104. throw new OutOfMemoryError();
    105. return (minCapacity > MAX_ARRAY_SIZE) ?
    106. Integer.MAX_VALUE :
    107. MAX_ARRAY_SIZE;
    108. }
    109. //获得大小
    110. public int size() {
    111. return size;
    112. }
    113. //判断是否为空
    114. public boolean isEmpty() {
    115. return size == 0;
    116. }
    117. //判断元素是否存在
    118. public boolean contains(Object o) {
    119. return indexOf(o) >= 0;
    120. }
    121. //遍历判断
    122. public int indexOf(Object o) {
    123. if (o == null) {
    124. for (int i = 0; i < size; i++)
    125. if (elementData[i] == null)
    126. return i;
    127. } else {
    128. for (int i = 0; i < size; i++)
    129. if (o.equals(elementData[i]))
    130. return i;
    131. }
    132. return -1;
    133. }
    134. public int lastIndexOf(Object o) {
    135. if (o == null) {
    136. for (int i = size - 1; i >= 0; i--)
    137. if (elementData[i] == null)
    138. return i;
    139. } else {
    140. for (int i = size - 1; i >= 0; i--)
    141. if (o.equals(elementData[i]))
    142. return i;
    143. }
    144. return -1;
    145. }
    146. public Object clone() {
    147. try {
    148. ArrayList<?> v = (ArrayList<?>) super.clone();
    149. v.elementData = Arrays.copyOf(elementData, size);
    150. v.modCount = 0;
    151. return v;
    152. } catch (CloneNotSupportedException e) {
    153. // this shouldn't happen, since we are Cloneable
    154. throw new InternalError(e);
    155. }
    156. }
    157. public Object[] toArray() {
    158. return Arrays.copyOf(elementData, size);
    159. }
    160. public <T> T[] toArray(T[] a) {
    161. if (a.length < size)
    162. // Make a new array of a's runtime type, but my contents:
    163. return (T[]) Arrays.copyOf(elementData, size, a.getClass());
    164. System.arraycopy(elementData, 0, a, 0, size);
    165. if (a.length > size)
    166. a[size] = null;
    167. return a;
    168. }
    169. //指定元素的数据
    170. E elementData(int index) {
    171. return (E) elementData[index];
    172. }
    173. //获得指定位置的元素
    174. public E get(int index) {
    175. //检查
    176. rangeCheck(index);
    177. //返回
    178. return elementData(index);
    179. }
    180. //指定位置替换元素
    181. public E set(int index, E element) {
    182. rangeCheck(index);
    183. E oldValue = elementData(index);
    184. elementData[index] = element;
    185. return oldValue;
    186. }
    187. //添加
    188. public boolean add(E e) {
    189. ensureCapacityInternal(size + 1); // Increments modCount!!
    190. elementData[size++] = e;
    191. return true;
    192. }
    193. //带位置的添加
    194. public void add(int index, E element) {
    195. //位置检查
    196. rangeCheckForAdd(index);
    197. //确保数组已使用长度(size)加1之后足够存下 下一个数据
    198. ensureCapacityInternal(size + 1);
    199. //使用System.arraycopy 将需要插入的位置(index)后面的元素统统往后移动一位。
    200. System.arraycopy(elementData, index, elementData, index + 1,
    201. size - index);
    202. //指定位置放元素
    203. elementData[index] = element;
    204. size++;
    205. }
    206. //删除
    207. public E remove(int index) {
    208. //检查位置
    209. rangeCheck(index);
    210. //操作数加1
    211. modCount++;
    212. //删除的元素
    213. E oldValue = elementData(index);
    214. //
    215. int numMoved = size - index - 1;
    216. // 将指定位置(index)上的元素都往前移动一位
    217. if (numMoved > 0)
    218. System.arraycopy(elementData, index + 1, elementData, index,
    219. numMoved);
    220. //后面的一个元素置空
    221. elementData[--size] = null; // clear to let GC do its work
    222. return oldValue;
    223. }
    224. //根据对象的位置进行删除
    225. public boolean remove(Object o) {
    226. if (o == null) {
    227. for (int index = 0; index < size; index++)
    228. if (elementData[index] == null) {
    229. fastRemove(index);
    230. return true;
    231. }
    232. } else {
    233. for (int index = 0; index < size; index++)
    234. if (o.equals(elementData[index])) {
    235. fastRemove(index);
    236. return true;
    237. }
    238. }
    239. return false;
    240. }
    241. //删除指定位置的元素
    242. private void fastRemove(int index) {
    243. modCount++;
    244. int numMoved = size - index - 1;
    245. if (numMoved > 0)
    246. System.arraycopy(elementData, index + 1, elementData, index,
    247. numMoved);
    248. elementData[--size] = null; // clear to let GC do its work
    249. }
    250. //添加操作次数(modCount),将数组内的元素都置空,等待垃圾收集器收集,不减小数组容量。
    251. public void clear() {
    252. modCount++;
    253. // clear to let GC do its work
    254. for (int i = 0; i < size; i++)
    255. elementData[i] = null;
    256. size = 0;
    257. }
    258. public boolean addAll(Collection<? extends E> c) {
    259. Object[] a = c.toArray();
    260. int numNew = a.length;
    261. ensureCapacityInternal(size + numNew); // Increments modCount
    262. System.arraycopy(a, 0, elementData, size, numNew);
    263. size += numNew;
    264. return numNew != 0;
    265. }
    266. public boolean addAll(int index, Collection<? extends E> c) {
    267. rangeCheckForAdd(index);
    268. Object[] a = c.toArray();
    269. int numNew = a.length;
    270. ensureCapacityInternal(size + numNew); // Increments modCount
    271. int numMoved = size - index;
    272. if (numMoved > 0)
    273. System.arraycopy(elementData, index, elementData, index + numNew,
    274. numMoved);
    275. System.arraycopy(a, 0, elementData, index, numNew);
    276. size += numNew;
    277. return numNew != 0;
    278. }
    279. //检查获得的位置是否合法
    280. private void rangeCheck(int index) {
    281. if (index >= size)
    282. throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    283. }
    284. /**
    285. * 检查添加位置是否合法
    286. */
    287. private void rangeCheckForAdd(int index) {
    288. if (index > size || index < 0)
    289. throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    290. }
    291. private String outOfBoundsMsg(int index) {
    292. return "Index: " + index + ", Size: " + size;
    293. }
    294. public boolean removeAll(Collection<?> c) {
    295. Objects.requireNonNull(c);
    296. return batchRemove(c, false);
    297. }
    298. public boolean retainAll(Collection<?> c) {
    299. Objects.requireNonNull(c);
    300. return batchRemove(c, true);
    301. }
    302. private boolean batchRemove(Collection<?> c, boolean complement) {
    303. final Object[] elementData = this.elementData;
    304. int r = 0, w = 0;
    305. boolean modified = false;
    306. try {
    307. for (; r < size; r++)
    308. if (c.contains(elementData[r]) == complement)
    309. elementData[w++] = elementData[r];
    310. } finally {
    311. // Preserve behavioral compatibility with AbstractCollection,
    312. // even if c.contains() throws.
    313. if (r != size) {
    314. System.arraycopy(elementData, r,
    315. elementData, w,
    316. size - r);
    317. w += size - r;
    318. }
    319. if (w != size) {
    320. // clear to let GC do its work
    321. for (int i = w; i < size; i++)
    322. elementData[i] = null;
    323. modCount += size - w;
    324. size = w;
    325. modified = true;
    326. }
    327. }
    328. return modified;
    329. }
    330. }