ArrayListレプリケーション

2217 ワード

1,既存の集合A,新規の集合B,Aの内容を完全にBにコピーしたい
public class Person implements Cloneable{
        private String name;
        private String hobby;
        private int age;
        public Person(String name, String hobby, int age) {
            this.name = name;
            this.hobby = hobby;
            this.age = age;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public String getHobby() {
            return hobby;
        }
        public void setHobby(String hobby) {
            this.hobby = hobby;
        }
        public int getAge() {
            return age;
        }
        public void setAge(int age) {
            this.age = age;
        }
        @Override
        public String toString() {
            return "habaobei{" +
                    "name='" + name + '\'' +
                    ", hobby='" + hobby + '\'' +
                    ", age=" + age +
                    '}';
        }
        public Person clone(){
            try {
                return (Person)super.clone();
            }catch (Exception var2) {
                return null;
            }
        }

}

addAll()メソッドにより、レプリケーションを実現し、
private static void testCloneForlist(){
    ArrayList qiao = new ArrayList<>();
    qiao.add(new Person("qiao haha","maimaimai",18));
    qiao.add(new Person("sha haha","maimaimai",19));
    List qiaosan = new ArrayList<>();
    List qiaosan2 = new ArrayList<>();
    qiaosan2.addAll(qiao);//addAll()
    for (Person habaobei :qiao)
    {
        Person haha = habaobei.clone();
        haha.setAge(20);
        qiaosan.add(haha);
    }
    System.out.println(qiao);
    System.out.println(qiaosan);
    System.out.println(qiaosan2);    
    for (Person habaobei :qiao)
    {
            habaobei.setAge(21);
    }
    System.out.println(qiao);
}
クラスのレプリケーションを実現するには、Cloneableを実現し、cloneメソッドを書き換える必要がある.