Employee[] a = new Employee[100]; // ... // array is full a = Arrays.copyOf(a, 2 * a.length);
如何編寫這樣一個通用的 copyOf 方法呢?java
// 不夠好的實現 public static Object[] badCopyOf(Object[] a, int newLength){ Object[] newArray = new Object[newLength]; System.arraycopy(a, 0, newArray, 0, Math.min(a.length, newLength)); return newArray; } // 好的實現 public static Object goodCopyOf(Object a, int newLength){ // 聲明爲 Object 而不是 Object[] 好處:能夠擴展任意類型數組,例如 int[] Class cl = a.getClass(); if(!cl.isArray()) return null; Class componentType = cl.getComponentType(); int length = Array.getLength(a); Object newArray = Array.newInstance(componentType, newLength); System.arraycopy(a, 0, newArray, 0, Math.min(a.length, newLength)); return newArray; }