Java入門–配列のdeepcopyを実現する方法

1.JavaBeanクラス
class Employee implements Serializable{
private int age;
private String name;

public Employee(){};
public Employee(int age,String name){
this.age=age;
this.name=name;
}

public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}

public String toString(){
return this.name+"–>"+this.age;
}

}
2.Listを出力
public static <T> void printList(List<T> list){
System.out.println(“—begin print list—“);
for(T t : list){
System.out.println(t);
}
System.out.println(“—end print list—“);
}

3.配列を出力
public static <T> void printArray(T[] array){
System.out.println(“—begin print array —“);
for(T t : array){
System.out.println(t);
}
System.out.println(“—end print array—“);
}
4.deepCopyの実現方法
public static <T> List<T> deepCopyFunc(List<T> src) throws IOException, ClassNotFoundException {
ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(byteOut);
out.writeObject(src);

ByteArrayInputStream byteIn = new ByteArrayInputStream(byteOut.toByteArray());
ObjectInputStream in = new ObjectInputStream(byteIn);
@SuppressWarnings(“unchecked")
List<T> dest = (List<T>) in.readObject();
return dest;
}
List<Employee> destList=deepCopyFunc(srcList);
printList(destList);
srcList.get(0).setAge(100);
printList(destList);

Java

Posted by arkgame