package org;
import java.util.ArrayList;
import java.util.List;
public class Test {
static class Dog {
public String color;
public Integer age;
}
public static void main(String[] args) {
Dog dog = new Dog();
dog.color = "yellow";
ArrayList<Dog> list = new ArrayList<>();
list.add(dog);
// list.add("2");
// list.add("3");
List<Dog> list2 = (List<Dog>)list.clone();
Dog dogClone = list2.get(0);
dogClone.color = "black";
System.out.println(list.get(0).color + list2.get(0).color);
}
}
// 输入的都是black
ArrayList的copy的源码
/**
* Returns a shallow copy of this <tt>ArrayList</tt> instance. (The
* elements themselves are not copied.)
*
* @return a clone of this <tt>ArrayList</tt> instance
*/
public Object clone() {
try {
ArrayList<?> v = (ArrayList<?>) super.clone();
v.elementData = Arrays.copyOf(elementData, size);
v.modCount = 0;
return v;
} catch (CloneNotSupportedException e) {
// this shouldn't happen, since we are Cloneable
throw new InternalError(e);
}
}
public static <T> T[] copyOf(T[] original, int newLength) {
return (T[]) copyOf(original, newLength, original.getClass());
}
public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) {
@SuppressWarnings("unchecked")
T[] copy = ((Object)newType == (Object)Object[].class)
? (T[]) new Object[newLength]
: (T[]) Array.newInstance(newType.getComponentType(), newLength);
System.arraycopy(original, 0, copy, 0,
Math.min(original.length, newLength));
return copy;
}