克隆基类的列表

时间:2012-07-04 23:18:59

标签: java netbeans clone

我有一个名为AddressType的基类

我还有两个名为HouseholdAddressType,PersonalAddressType的子类。 (所以这些都扩展了AddressType)

我传递了一个AddressType列表:

List<AddressType> addresses

到很多方法,并且预先形成不同的任务,因此我想在预先形成这些任务之前克隆这个列表。

我试过这个:

List<AddressType> copyOfAddress = new ArrayList<AddressType>(addresses.size());
    for (AddressType addressType: addresses) {
        copyOfAddress.add((AddressType)addressType.clone());         
    }

然而,它无法说明:“克隆具有受保护的访问权”

如何克隆此列表? 我的班级名称的例子会很好..非常感谢

1 个答案:

答案 0 :(得分:3)

班级AddressType必须实施Cloneable界面

import java.util.ArrayList;
import java.util.List;


public class Foo {
    public static void main(String[] args) {

        List<Person> oldList = new ArrayList<Person>(1);
        oldList.add(new Person("Harry", "Potter"));

        List<Person> newList = new ArrayList<Person>();
        for(Person person : oldList)
        {
            newList.add(person.clone()); // Deep copy of each person too.
        }

        Person person = newList.get(0);
        person.setFirstName("James");

        System.out.println("Old list = " + oldList);
        System.out.println("New list = " + newList);
    }

    static class Person implements Cloneable
    {
        private String firstName;
        private String lastName;

        Person(String firstName, String lastName)
        {
            this.firstName = firstName;
            this.lastName = lastName;
        }

        private Person(Person person)
        {
            this.firstName = person.firstName;
            this.lastName = person.lastName;
        }

        public void setFirstName(String firstName)
        {
            this.firstName = firstName;
        }

        public String getFirstName()
        {
            return firstName;
        }

        public void setLastName(String lastName)
        {
            this.lastName = lastName;
        }

        public String getLastName()
        {
            return lastName;
        }

        @Override
        public String toString()
        {
            StringBuilder sb = new StringBuilder();

            sb.append(firstName);
            sb.append(" ");
            sb.append(lastName);

            return sb.toString();
        }

        @Override
        public Person clone()
        {
            return new Person(this);
        }
    }
}

输出

Old list = [Harry Potter]
New list = [James Potter]