- 定义一个Car类型的类,其中只有一个int类型的id属性
- 创建一个Car类型的实例,c,id设置成1
- 通过new创建两个不同的ArrayList,a1和a2,c对象分别放入a1和a2
- 在a1这个ArrayList里,拿出c对象,并把id设置成2,同时不对存放在a2里的c对象做任何的修改
- 问题是,完成上述步骤,a2里存放的c对象的id是多少?1还是2?
import java.util.ArrayList;
class Car{
private int id;
public Car(int id){
this.id = id;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
public class Test1 {
public static void main(String[] args){
Car c = new Car(1);
ArrayList<Car> a1 = new ArrayList<Car>();
ArrayList<Car> a2 = new ArrayList<Car>();
a1.add(c);
a2.add(c);
a1.get(0).setId(2);
System.out.println(a2.get(0).getId());
}
}
输出结果为:2
import java.util.ArrayList;
class CarDeepCopy implements Cloneable{
private int id;
public CarDeepCopy(int id){
this.id = id;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Object Clone() throws CloneNotSupportedException{
return super.clone();
}
}
public class Test2 {
public static void main(String[] args){
CarDeepCopy c1 = new CarDeepCopy(1);
CarDeepCopy c2 = null;
try{
c2 = (CarDeepCopy) c1.Clone();
} catch(CloneNotSupportedException e) {
e.printStackTrace();
}
ArrayList<CarDeepCopy> a1 = new ArrayList<CarDeepCopy>();
ArrayList<CarDeepCopy> a2 = new ArrayList<CarDeepCopy>();
a1.add(c1);
a2.add(c2);
a1.get(0).setId(2);
System.out.println(a2.get(0).getId());
}
}
输出结果:1