Java ArrayList 源码解析

"Java"

Java 是一门面向对象编程语言,是支持继承、多态等特性的,这里 ArrayList 这个库呢,继承了 AbstractList (抽象数组)库

1 2 3 4 5 6 7 
java.lang.Object  ↳     java.util.AbstractCollection<E>  ↳     java.util.AbstractList<E>  ↳     java.util.ArrayList<E> //ArrayList 继承关系  public class ArrayList<E> extends AbstractList<E>  implements List<E>, RandomAccess, Cloneable, java.io.Serializable {} //注意看这里 

大概就这个样子

注意看第 7 行,通过继承,ArrayList 实现了 List,RandomAccess,Cloneable,java.io.Serializable等接口

  • List:实现了数组的基本功能
  • RandomAccess:这个这里不多讲,顾名思义,是一个创建快速随机访问的函数,提高效率
  • Cloneable:字面意思,实现了 clone() 函数,可被克隆
  • java.io.Serializable:支持了序列化的传输

构造函数

1 2 3 4 5 
ArrayList()  ArrayList(int capacity) // capacity 创建默认容量,容量是动态的,不足时会增加一半  ArrayList(Collection<? extends E> collection) // 这里包含了 collection 

熟悉 collection 和 ArrayList 的朋友会发现,两者真的很像,中间的差距在于一个对象:elementData

  • elementData:真正的核心实现,本质就是个动态数组,用于保存 ArrayList 中的元素

API

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 
// 继承于 Collection boolean add(E object) boolean addAll(Collection<? extends E> collection) void clear() boolean contains(Object object) boolean containsAll(Collection<?> collection) boolean equals(Object object) int hashCode() boolean isEmpty() Iterator<E> iterator() boolean remove(Object object) boolean removeAll(Collection<?> collection) boolean retainAll(Collection<?> collection) int size() <T> T[] toArray(T[] array) Object[] toArray() // 继承于 AbstractCollection void add(int location, E object) boolean addAll(int location, Collection<? extends E> collection) E get(int location) int indexOf(Object object) int lastIndexOf(Object object) ListIterator<E> listIterator(int location) ListIterator<E> listIterator() E remove(int location) E set(int location, E object) List<E> subList(int start, int end) // ArrayList 新增 Object clone() void ensureCapacity(int minimumCapacity) void trimToSize() void removeRange(int fromIndex, int toIndex) 

源码分析:重头戏

重头戏来了,请好好读注释

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 
package java.util;  public class ArrayList<E> extends AbstractList<E>  implements List<E>, RandomAccess, Cloneable, java.io.Serializable {  private static final long serialVersionUID = 8683452581122892189L;   // 刚才提到的 elementData,用于存储数值的数组  private transient Object[] elementData;   // 目前的实际数组大小  private int size;   // 默认构造函数,带有初始容量(initial)  public ArrayList(int initialCapacity) {  super();  if (initialCapacity < 0)  throw new IllegalArgumentException("Illegal Capacity: "+  initialCapacity);  // 新建数组  this.elementData = new Object[initialCapacity];  }   // 未声明初始容量的时候,默认为 10  public ArrayList() {  this(10);  }   // 创建一个包含 collection 的 ArrayList  public ArrayList(Collection<? extends E> c) {  elementData = c.toArray();  size = elementData.length;  // c.toArray might (incorrectly) not return Object[] (see 6260652)  if (elementData.getClass() != Object[].class)  elementData = Arrays.copyOf(elementData, size, Object[].class);  }    // 动态调整容量,将容量设为实际元素个数  public void trimToSize() {  modCount++;  int oldCapacity = elementData.length;  if (size < oldCapacity) {  elementData = Arrays.copyOf(elementData, size);  }  }    // 如果容量不足,扩展数组:容量=(容量x3)/2 + 1  public void ensureCapacity(int minCapacity) {  modCount++;  int oldCapacity = elementData.length;  // 如果容量不足,扩展数组:容量=(容量x3)/2 + 1  if (minCapacity > oldCapacity) {  Object oldData[] = elementData;  int newCapacity = (oldCapacity * 3)/2 + 1;  if (newCapacity < minCapacity)  newCapacity = minCapacity;  elementData = Arrays.copyOf(elementData, newCapacity);  }  }   // 添加元素e  public boolean add(E e) {  ensureCapacity(size + 1); // Increments modCount!!  // 添加e到ArrayList中  elementData[size++] = e;  return true;  }   // 返回实际大小  public int size() {  return size;  }   public boolean contains(Object o) {  return indexOf(o) >= 0;  }   // 检查 ArrayList 是否为空  public boolean isEmpty() {  return size == 0;  }   // 正向查找元素的索引值  // 这里跟 String Methods 的各种函数都差不多  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;  }   // 反向查找元素的索引值  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;  }   // 反向查找元素(o)的索引值  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[] toArray() {  return Arrays.copyOf(elementData, size);  }   public <T> T[] toArray(T[] a) {  // 新建一个T[]数组,数组大小是目前元素数,克隆数组元素  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;  }   // 获取 index 位置的元素值  // 类似 charAt  public E get(int index) {  RangeCheck(index);   return (E) elementData[index];  }   public E set(int index, E element) {  RangeCheck(index);   E oldValue = (E) elementData[index];  elementData[index] = element;  return oldValue;  }   public boolean add(E e) {  ensureCapacity(size + 1); // Increments modCount!!  elementData[size++] = e;  return true;  }   // 将 e 添加到ArrayList的指定位置  public void add(int index, E element) {  if (index > size || index < 0)  throw new IndexOutOfBoundsException(  "Index: "+index+", Size: "+size);   ensureCapacity(size+1); // Increments modCount!!  System.arraycopy(elementData, index, elementData, index + 1,  size - index);  elementData[index] = element;  size++;  }   // 删除指定位置的元素  public E remove(int index) {  RangeCheck(index);   modCount++;  E oldValue = (E) elementData[index];   int numMoved = size - index - 1;  if (numMoved > 0)  System.arraycopy(elementData, index+1, elementData, index,  numMoved);  elementData[--size] = null; // Let gc do its work   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;  }    // 快速删除第 index 个元素  private void fastRemove(int index) {  modCount++;  int numMoved = size - index - 1;  // 从 index+1 开始,用后面的元素替换前面的元素  //位移  if (numMoved > 0)  System.arraycopy(elementData, index+1, elementData, index,  numMoved);  // 将最后一个元素设为 null  elementData[--size] = null; // Let gc do its work  }   // 删除元素  // 区别在于这里需要查找元素  public boolean remove(Object o) {  if (o == null) {  for (int index = 0; index < size; index++)  if (elementData[index] == null) {  fastRemove(index);  return true;  }  } else {  // 便利 ArrayList,找到 元素o,删除  for (int index = 0; index < size; index++)  if (o.equals(elementData[index])) {  fastRemove(index);  return true;  }  }  return false;  }   // 清空ArrayList  public void clear() {  modCount++;   for (int i = 0; i < size; i++)  elementData[i] = null;   size = 0;  }   // 将集合 c 加到 ArrayList 中  public boolean addAll(Collection<? extends E> c) {  Object[] a = c.toArray();  int numNew = a.length;  ensureCapacity(size + numNew); // Increments modCount  System.arraycopy(a, 0, elementData, size, numNew);  size += numNew;  return numNew != 0;  }   // 从 index 位置开始,将集合 c 添加到 ArrayList  public boolean addAll(int index, Collection<? extends E> c) {  if (index > size || index < 0)  throw new IndexOutOfBoundsException(  "Index: " + index + ", Size: " + size);   Object[] a = c.toArray();  int numNew = a.length;  ensureCapacity(size + numNew); // Increments modCount   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;  }   // 删除fromIndex 到toIndex 之间的全部元素  protected void removeRange(int fromIndex, int toIndex) {  modCount++;  int numMoved = size - toIndex;  System.arraycopy(elementData, toIndex, elementData, fromIndex,  numMoved);   // Let gc do its work  int newSize = size - (toIndex-fromIndex);  while (size != newSize)  elementData[--size] = null;  }   private void RangeCheck(int index) {  if (index >= size)  throw new IndexOutOfBoundsException(  "Index: "+index+", Size: "+size);  }    // 克隆函数  public Object clone() {  try {  ArrayList<E> v = (ArrayList<E>) super.clone();  // 将当前 ArrayList 的全部元素克隆到 v 中  v.elementData = Arrays.copyOf(elementData, size);  v.modCount = 0;  return v;  } catch (CloneNotSupportedException e) {  // this shouldn't happen, since we are Cloneable  throw new InternalError();  }  }    // java.io.Serializabl e的写入函数  // 将ArrayList的 容量、元素值 都写入到输出流中  private void writeObject(java.io.ObjectOutputStream s)  throws java.io.IOException{  // Write out element count, and any hidden stuff  int expectedModCount = modCount;  s.defaultWriteObject();   // 写入数组的容量  s.writeInt(elementData.length);   // 写入元素  for (int i=0; i<size; i++)  s.writeObject(elementData[i]);   if (modCount != expectedModCount) {  throw new ConcurrentModificationException();  }   }    // java.io.Serializable 的读取函数,基本一致  private void readObject(java.io.ObjectInputStream s)  throws java.io.IOException, ClassNotFoundException {  s.defaultReadObject();   int arrayLength = s.readInt();  Object[] a = elementData = new Object[arrayLength];   for (int i=0; i<size; i++)  a[i] = s.readObject();  } } 

所以这里其实挺清晰的,就是用了一个 elementData 动态数组来存取数据
容量变化规则:容量=(容量x3)/2 + 1

诚然,效率肯定比 List 低,但是这个时代每台计算机的内存都早早突破了这些限制,这个效率差距几乎没有影响,主要是动态的容量能够快速的删除、存取大量数据,节省了大量的存储空间

使用 ArrayList

1 2 3 4 5 6 7 8 9 10 
import java.util.ArrayList; // 调用库  public class Example {  public static void main(String []args)  {  ArrayList list = new ArrayList();  // ...  } } 

结语

随手写写,看着 ArrayList 的源码随手加注释,也算是加深自己的理解吧
如有雷同,纯属偶然,毕竟看代码写注释都差不多

其实大家可以看看官方 Doc

本文来自网络

本博客所有文章如无特别注明均为原创。作者:小乐复制或转载请以超链接形式注明转自 众众帮
原文地址《Java ArrayList 源码解析
分享到:更多

相关推荐

发表评论

路人甲 表情
Ctrl+Enter快速提交

网友评论(0)