/** * Creates and returns a copy of this object. The precise meaning * of "copy" may depend on the class of the object. The general * intent is that, for any object {@code x}, the expression: * <blockquote> * <pre> * x.clone() != x</pre></blockquote> * will be true, and that the expression: * <blockquote> * <pre> * x.clone().getClass() == x.getClass()</pre></blockquote> * will be {@code true}, but these are not absolute requirements. * While it is typically the case that: * <blockquote> * <pre> * x.clone().equals(x)</pre></blockquote> * will be {@code true}, this is not an absolute requirement. * <p> * By convention, the returned object should be obtained by calling * {@code super.clone}. If a class and all of its superclasses (except * {@code Object}) obey this convention, it will be the case that * {@code x.clone().getClass() == x.getClass()}. * <p> * ... */ protected native Object clone() throws CloneNotSupportedException;
int [] ages = newint[] {1,2,3,4}; int[] ints = Arrays.copyOf(ages, 2);//输出[1,2] // 我们还是来看源码 /** * Copies the specified array, truncating or padding with zeros (if necessary) * so the copy has the specified length. For all indices that are * valid in both the original array and the copy, the two arrays will * contain identical values. For any indices that are valid in the * copy but not the original, the copy will contain <tt>0</tt>. * Such indices will exist if and only if the specified length * is greater than that of the original array. * * @param original the array to be copied * @param newLength the length of the copy to be returned * @return a copy of the original array, truncated or padded with zeros * to obtain the specified length * @throws NegativeArraySizeException if <tt>newLength</tt> is negative * @throws NullPointerException if <tt>original</tt> is null * @since 1.6 */ publicstaticint[] copyOf(int[] original, int newLength) { int[] copy = newint[newLength]; System.arraycopy(original, 0, copy, 0, Math.min(original.length, newLength)); return copy; } publicstaticnativevoidarraycopy(Object src, int srcPos, Object dest, int destPos, int length); // 从源码 我们可以看到 Arrays.copyOf()最终调用的是native本地方法栈的方法,我们知道本地方法都是直接操作内存的,那么源对象变了,因为都是指向同一个内存地址,所以拷贝对象肯定跟着变,所以此种方法也是浅拷贝;