调用Arrays.copyOf()方法会在堆中重新分配内存创建数组
代码翻译:
/传入原有数组对象,传入要截取的长度 public static <T> T[] copyOf(T[] original, int newLength) { return (T[]) copyOf(original, newLength, original.getClass()); } //传入原有数组对象,传入要截取的长度、数组中的类newType public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) { @SuppressWarnings("unchecked") //新建一个长度为newLenth的数组 T[] copy = ((Object)newType == (Object)Object[].class) ? (T[]) new Object[newLength] : (T[]) Array.newInstance(newType.getComponentType(), newLength); //通过System.arraycopy方法将原有数组拷贝到新的数组中,最后返回新数组 System.arraycopy(original, 0, copy, 0, Math.min(original.length, newLength)); return copy; }
测试:
public static void main(String[] args) { String[] arrayOld = {"1","2"}; System.out.println(JSONObject.toJSONString(arrayOld)); System.out.println("arrayOld="+arrayOld); String[] araryNew = arrayOld; System.out.println(JSONObject.toJSONString(araryNew)); System.out.println("araryNew="+araryNew); String[] araryCopy = Arrays.copyOf(araryNew, araryNew.length); System.out.println(JSONObject.toJSONString(araryCopy)); System.out.println("araryCopy="+araryCopy); }
执行结果:
["1","2"]
arrayOld=[Ljava.lang.String;@60f82f98
["1","2"]
araryNew=[Ljava.lang.String;@60f82f98
["1","2"]
araryCopy=[Ljava.lang.String;@35f983a6
arrayOld与araryCopy对象不同,说明 Arrays.copyOf()会在堆中重新分配内存创建数组