复制存储在HashMap中的对象并将其添加到ArrayList

时间:2015-12-17 14:10:30

标签: java arraylist hashmap

假设我有一个名为Entity的类,另一个名为Crate的类,它扩展了此实体。然后我将此Crate添加到实体entityTypes的HashMap中,其中键是“Crate”。如何将此包的新实例添加到ArrayList?

class Entity {
    // stuff
}

class Crate {
    // stuff
    public Crate() {
        System.out.println("hi there");
    }
}

class Main {
    public void foo() {
         HashMap<String, Entity> entityTypes = new HashMap<String, Entity>();
         entityTypes.put("Crate", new Crate());

         ArrayList<Entity> entities = new ArrayList<Entity>();
         entities.add(entityTypes.get("Crate")); // create a new instance here?
    }
}

如果我要运行该代码,Crate构造函数仅在我将其添加到HashMap时调用一次。当我将它添加到arraylist时,有什么方法可以创建一个新的实例吗?

1 个答案:

答案 0 :(得分:0)

您可以在Entity类中放置一个方法来生成新实例。

class Entity {
    public Entity newInstance() {
        return new Entity();
    }
}

并让子类相应地覆盖它:

class Crate extends Entity {
    @Override
    public Entity newInstance() { 
        return new Crate();
    }
}

然后,当您从HashMap

中提取内容时,您可以调用该方法
List<Entity> entities = new ArrayList<Entity>();
entities.add(entityTypes.get("Crate").newInstance());

假设您的对象比您的示例更复杂,您可能希望定义一个复制构造函数,并从newInstance()调用它。在这种情况下,我会将方法重命名为copy()。例如:

class Entity {
    public Entity copy() {
        return new Entity();
    }
}

class Crate extends Entity {
    private String id;

    public Crate(Crate other) {
        // Copy whatever you need here from the other Crate object
        this.id = other.id;
    }

    @Override
    public Entity copy() {
        return new Crate(this);
    }
}

然后调用它变为:

List<Entity> entities = new ArrayList<Entity>();
entities.add(entityTypes.get("Crate").copy());