深拷贝和浅拷贝

  • 定义一个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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值