如何编写这样一个通用的 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; }转载于:https://www.cnblogs.com/hiwangzi/p/7668254.html
相关资源:三年JavaEE开发积累的那些代码之一:JavaSE篇完整实例源码