|
55 | 55 |
|
56 | 56 | 由此可见 `ArrayList` 的主要消耗是数组扩容以及在指定位置添加数据,在日常使用时最好是指定大小,尽量减少扩容。更要减少在指定位置插入数据的操作。
|
57 | 57 |
|
| 58 | +### 序列化 |
| 59 | + |
| 60 | +由于 ArrayList 是基于动态数组实现的,所以并不是所有的空间都被使用,所以使用了 `transient` 修饰,可以防止被序列化。 |
| 61 | + |
| 62 | +```java |
| 63 | +transient Object[] elementData; |
| 64 | +``` |
| 65 | + |
| 66 | +因此 ArrayList 自定义了序列化与反序列化: |
| 67 | + |
| 68 | +```java |
| 69 | + private void writeObject(java.io.ObjectOutputStream s) |
| 70 | + throws java.io.IOException{ |
| 71 | + // Write out element count, and any hidden stuff |
| 72 | + int expectedModCount = modCount; |
| 73 | + s.defaultWriteObject(); |
| 74 | + |
| 75 | + // Write out size as capacity for behavioural compatibility with clone() |
| 76 | + s.writeInt(size); |
| 77 | + |
| 78 | + // Write out all elements in the proper order. |
| 79 | + //只序列化了被使用的数据 |
| 80 | + for (int i=0; i<size; i++) { |
| 81 | + s.writeObject(elementData[i]); |
| 82 | + } |
| 83 | + |
| 84 | + if (modCount != expectedModCount) { |
| 85 | + throw new ConcurrentModificationException(); |
| 86 | + } |
| 87 | + } |
| 88 | + |
| 89 | + private void readObject(java.io.ObjectInputStream s) |
| 90 | + throws java.io.IOException, ClassNotFoundException { |
| 91 | + elementData = EMPTY_ELEMENTDATA; |
| 92 | + |
| 93 | + // Read in size, and any hidden stuff |
| 94 | + s.defaultReadObject(); |
| 95 | + |
| 96 | + // Read in capacity |
| 97 | + s.readInt(); // ignored |
| 98 | + |
| 99 | + if (size > 0) { |
| 100 | + // be like clone(), allocate array based upon size not capacity |
| 101 | + ensureCapacityInternal(size); |
| 102 | + |
| 103 | + Object[] a = elementData; |
| 104 | + // Read in all elements in the proper order. |
| 105 | + for (int i=0; i<size; i++) { |
| 106 | + a[i] = s.readObject(); |
| 107 | + } |
| 108 | + } |
| 109 | + } |
| 110 | +``` |
| 111 | + |
| 112 | +> 当对象中自定义了 writeObject 和 readObject 方法时,JVM 会调用这两个自定义方法来实现序列化与反序列化。 |
| 113 | +
|
| 114 | + |
| 115 | +从实现中可以看出 ArrayList 只序列化了被使用的数据。 |
| 116 | + |
58 | 117 |
|
59 | 118 | ## Vector
|
60 | 119 |
|
|
0 commit comments