今天被問到Java的Array(陣列)與ArrayList的差別。
當下我只回說ArrayList的元素只能是物件,而ArrayList實際上是對Array進行包裝提供一些好用的操作方法之類。總之回答得亂七八糟,因此這邊做個整理。
int[] ints = new int[10]; // 陣列Array
ArrayList intList = new ArrayList(10); // ArrayList
- Array的大小是固定的;
ArrayList的大小是可變的。 - Array中的元素可以是原始型別(primitive)或物件(object);
ArrayList的元素只能是物件。 - Array不能使用泛型(generic),
ArrayList可以使用泛型。 - Array用
length屬性取得內容長度;ArrayList用size()方法取得內容長度。 - Array用賦值符(
=)儲存元素值;ArrayList用add()方法儲存元素值。
ArrayList內部實際上是透過陣列Object[] elementData來維護儲存的元素,所以元素必須為物件型態,不能是原始型別,因為這樣才能達到泛型的效果。
節錄原始碼如下。
ArrayList
public class ArrayList<E> extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{
...
/**
* 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
...
}
查到答案後很快就想起這些差別,但面試的時候這可不是理由,只能說自己基本功不夠紮實。
沒有留言:
張貼留言