[基本]Javaオブジェクトclone
2406 ワード
import java.util.Date;
public class TestCloneEntry {
public static void main(String[] args) throws CloneNotSupportedException {
Employee itemA = new Employee("chendu", 12, new Date());
Employee copyA = itemA;
copyA.setAge(15);
System.out.println("use =");
System.out.println("itemA:"+itemA.getAge());
System.out.println("copyA:"+copyA.getAge());
System.out.println();
Employee itemB = new Employee("chendu", 13, new Date());
Employee copyB = itemB.clone();
copyB.setAge(16);
System.out.println("use clone");
System.out.println("itemB:"+itemB.getAge());
System.out.println("copyB:"+copyB.getAge());
}
}
/*
* if want to use Clone, must implement Coneable interface,
* overrige Clone() method and throws CloneNotSupportedException exception
* */
class Employee implements Cloneable{
private String name;
private int age;
private Date hireDay;
@Override
protected Employee clone() throws CloneNotSupportedException {
return (Employee)super.clone();
}
public Employee(){}
public Employee(String name, int age, Date hireDay) {
this.name = name;
this.age = age;
this.hireDay = hireDay;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Date getHireDay() {
return hireDay;
}
public void setHireDay(Date hireDay) {
this.hireDay = hireDay;
}
}
use =
itemA:15
copyA:15
use clone
itemB:13
copyB:16
//arrays always has a Clone() method, but ArrayList not
import java.util.Arrays;
import java.util.List;
public class TestCloneArray {
public static void main(String[] args) {
int[] itemC = {6,2,7,8};
int[] cloneC = itemC.clone();
cloneC[3] = 5;
System.out.println("itemC"+Arrays.toString(itemC));
System.out.println("cloneC"+Arrays.toString(cloneC));
System.out.println();
List<Integer> itemD = Arrays.asList(6,2,7,8);
List<Object> cloneD = Arrays.asList(itemD.toArray());
cloneD.set(3, 5);
System.out.println("itemD"+itemD.toString());
System.out.println("cloneD"+cloneD.toString());
}
}
itemC[6, 2, 7, 8]
cloneC[6, 2, 7, 5]
itemD[6, 2, 7, 8]
cloneD[6, 2, 7, 5]