ArrayList 原理、 擴容機制
阿新 • • 發佈:2019-01-09
我們都知道一個物件只要實現了Serilizable介面,這個物件就可以被序列化,java的這種序列化模式為開發者提供了很多便利,我們可以不必關係具體序列化的過程,只要這個類實現了Serilizable介面,這個的所有屬性和方法都會自動序列化。
然而在實際開發過程中,我們常常會遇到這樣的問題,這個類的有些屬性需要序列化,而其他屬性不需要被序列化。java的transient關鍵字為我們提供了便利,你只需要實現Serilizable介面,將不需要序列化的屬性前新增關鍵字transient,序列化物件的時候,這個屬性就不會序列化到指定的目的地中。
Java的ArrayList中,定義了一個數組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.
- */
- transient Object[] elementData; // non-private to simplify nested class access
其實玄機在於ArrayList中的兩個方法:
-
/**
- * Save the state of the <tt>ArrayList</tt> instance to a stream (that
- * is, serialize it).
- *
- * @serialData The length of the array backing the <tt>ArrayList</tt>
- * instance is emitted (int), followed by all of its elements
- * (each an <tt>Object</tt>) in the proper order.
- */
- privatevoid writeObject(java.io.ObjectOutputStream s)
- throws java.io.IOException{
- // Write out element count, and any hidden stuff
- int expectedModCount = modCount;
- s.defaultWriteObject();
- // Write out size as capacity for behavioural compatibility with clone()
- s.writeInt(size);
- // Write out all elements in the proper order.
- for (int i=0; i<size; i++) {
- s.writeObject(elementData[i]);
- }
- if (modCount != expectedModCount) {
- thrownew ConcurrentModificationException();
- }
- }
- /**
- * Reconstitute the <tt>ArrayList</tt> instance from a stream (that is,
- * deserialize it).
- */
- privatevoid readObject(java.io.ObjectInputStream s)
- throws java.io.IOException, ClassNotFoundException {
- elementData = EMPTY_ELEMENTDATA;
- // Read in size, and any hidden stuff
- s.defaultReadObject();
- // Read in capacity
- s.readInt(); // ignored
- if (size > 0) {
- // be like clone(), allocate array based upon size not capacity
- ensureCapacityInternal(size);
- Object[] a = elementData;
- // Read in all elements in the proper order.
- for (int i=0; i<size; i++) {
- a[i] = s.readObject();
- }
- }
- }
為什麼不直接用elementData來序列化,而採用上訴的方式來實現序列化呢?原因在於elementData是一個快取陣列,它通常會預留一些容量,等容量不足時再擴充容量,那麼有些空間可能就沒有實際儲存元素,採用上訴的方式來實現序列化時,就可以保證只序列化實際儲存的那些元素,而不是整個陣列,從而節省空間和時間。