Employee[] a = new Employee[100];
// ...
// array is full
a = Arrays.copyOf(a, 2 * a.length);

如何编写这样一个通用的 copyOf 方法呢?

// 不够好的实现
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;
}
05-27 21:34