Say I had a class called Entity
, and another class called Crate
, which extends this Entity. I then add this Crate to a HashMap of Entities entityTypes
where the key is "Crate". How can I add a new instance of this crate to an 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?
}
}
If I were to run that code, the Crate constructor is only called once from when I add it to the HashMap. Is there any way I can make a new instance of this when I add it to the arraylist?