Java深浅拷贝

java的浅拷贝在复制了对象之后,在对cloned对象修改也会修改原来的对象属性。


具体看下面的代码,在进行代码的浅拷贝之后,原本的数据也被改变了。

package interfaces;

import java.awt.event.MouseWheelEvent;
import java.util.Arrays;

public class EmployeeSortTest {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Employee[] staff = new Employee[3];
        staff[0] = new Employee("sbc",3000);
        staff[1] = new Employee("abc", 4000);
        staff[2] = new Employee("def", 3500);
        
        Arrays.sort(staff);
        
        for(Employee employee :staff)
        {
            System.out.println("name="+employee.getName()+",salary="+employee.getSalary());
        }
        
        Employee aEmployee = new Employee("1", 2);
        
        Employee bEmployee = null;
        try {
            bEmployee = aEmployee.clone();
        } catch (CloneNotSupportedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        bEmployee.raiseSalary(10);
        System.out.println("aEmployee.salary="+aEmployee.getSalary());
        System.out.println("bEmployee.salary="+bEmployee.getSalary());
        Employee cEmployee = aEmployee;
        cEmployee.raiseSalary(20);
        System.out.println("aEmployee.salary="+aEmployee.getSalary());
        System.out.println("cEmployee.salary="+cEmployee.getSalary());
    }

}


//结果:
name=sbc,salary=3000.0
name=def,salary=3500.0
name=abc,salary=4000.0
aEmployee.salary=2.0
bEmployee.salary=2.2
aEmployee.salary=2.4
cEmployee.salary=2.4

1.在实现java的深拷贝需要我们implement一下接口{Cloneable}。

2.不管是深拷贝/浅拷贝都需要我们重写clone()这个方法。

3.实现clone()方法时,我们需要将方法权限改成public(原来权限的是protected)。

package interfaces;

public class Employee implements Comparable,Cloneable{
	private String name;
	private double salary;
	
	public Employee (String n,double s) {
		name = n;
		salary = s;
	}
	
	public String getName() {
		return name;
	}
	
	public double getSalary() {
		return salary;
	}
	
	public void raiseSalary(double byPercent) {
		double raise = salary*byPercent/100;
		salary += raise;
	}
	public int compareTo(Employee other) {
		return Double.compare(salary,other.salary);
	}
	
	public Employee clone() throws CloneNotSupportedException
	{
		Employee cloned = (Employee)super.clone();
		//按照道理我们应该克隆所有可变实例域
		//
		return cloned;
	}
	
}

你可能感兴趣的:(java)