Hello all, I have run into a bit of a dilemma in my program with regards to proper application of object cloning.
So here's what I am trying to make happen: I'm developing a small level editor for a game that I am making. In my game, I have an ArrayList containing all of the enemies in the game, each of which is an object. What I want to do is produce a second duplicate ArrayList that contains all of the same identical Enemy objects. This way I would be able to have an active, playable screen of my game, as well as an inactive one that can be used for editing, testing, and loading/saving levels.
After doing a bit of research, I discovered this approach: I add this method to the Enemy class and also add implementation to "cloneable":
protected Object clone() throws CloneNotSupportedException { return super.clone(); }
And then whenever I need to clone an object, I use something along the lines of this:
Enemy oldEnemy = new Enemy(); try { Enemy newEnemy = (Enemy) oldEnemy.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); }
This works for the most part, but there seems to be a fatal flaw. My Enemy ArrayList contains many different types of enemies that extend the Enemy Class, such as FlyingEnemy, ShootingEnemy, etc...
The above method of cloning only seems to work for a specific class, since I must cast it as an Enemy. Does anybody know how I might get it to work like I want? I have seen there are many different ways to clone an object, but I don't know which way would work the best for my purposes.
Thanks in advance to anybody who has advice!