0

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?

mosmo
  • 411
  • 1
  • 4
  • 10
  • 1
    I think you should first read java basics first. – geekprogrammer Dec 17 '15 at 14:16
  • You will need to explicitly [copy](http://stackoverflow.com/questions/869033/how-do-i-copy-an-object-in-java) your object. – dejvuth Dec 17 '15 at 14:16
  • 1
    you're not extending `Crate` class in this code :) also, what exactly do u want to add to the `ArrayList`, the same `Crate` object that lies in `entityTypes` or a **new** `Crate` object, i didn't get you? – solar Dec 17 '15 at 14:16
  • @solar woops, it's just rough code of a larger application – mosmo Dec 17 '15 at 14:35
  • @dejvuth Hm, I figured I would have to copy/clone it. I tried the answer by "Bhasker Tiwari" but it didn't seem to work. – mosmo Dec 17 '15 at 14:37

1 Answers1

0

You could put a method in your Entity class to generate a new instance.

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

And have subclasses override it accordingly:

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

Then you could call that method when you pull things from the HashMap:

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

Assuming your objects are more complex than your example, you would probably want to define a copy constructor, and invoke that from newInstance(). In this case, I would rename the method to copy(). Example:

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);
    }
}

Then invoking it becomes:

List<Entity> entities = new ArrayList<Entity>();
entities.add(entityTypes.get("Crate").copy());
nickb
  • 59,313
  • 13
  • 108
  • 143