Reputation: 23
I am new to OOP, and I'm trying to make a simple game to help me learn Java. My idea was to make an enemy class, but I want the amount of enemies to be dynamic. I tried making a new object as an array rather than manually typing attker1 attker2 and so on ...
Mole attacker[3];
attacker[0] = new Mole();
attacker[1] = new Mole();
attacker[2] = new Mole();
I hope you get the idea of what I'm trying to do. I've tried searching Google, but I keep getting tutorials on how to make arrays out of regular data types (i.e. int, char, etc.). I'd like to know what it's called, whatever I'm trying to do. If there is a better way of doing this I'll listen to that too.
Thank you.
Upvotes: 2
Views: 162
Reputation: 917
You should probably use Collections or Set like
http://download.oracle.com/javase/1.4.2/docs/api/java/util/List.html
http://download.oracle.com/javase/1.4.2/docs/api/java/util/HashSet.html
to get started, experts will empower your mole-extermination later on ;)
Upvotes: 0
Reputation: 4241
Arrays of objects are perfectly fine (indeed, often used more than simple arrays of primitive data types).
So, if you want the amount of enemies to be dynamic, you might want to use a Container class- specifically a resizable array. Look into classes Vector, ArrayList, etc.
Also note (I saw the Android tag) that creating new objects in the drawing loop can cause the Garbage Collector to be called and slow down the framerate while it works - be warned.
A variation on what you have:
//create enemies
Mole enemies[3];
enemies[0] = new Mole();
enemies[1] = new Mole();
enemies[2] = new Mole();
//an enemy dies!
enemies[1] = null;
//and comes back to life!
enemies[1] = new Mole();
//do something with your enemies....
Upvotes: 3
Reputation: 895
In Assuming you are talking about doing it in Java. Have you tried to search for List of Objects, List of Custom Classes ?
Take a look at the following:
Create List from Java Object Array Example
There are also other ways of doing it, such as Dictionary, ArrayList, or if your object implements other interfaces, you can choose to use other methods too, such as HashSet etc.
Hope you get a good start with List or ArrayList etc
Upvotes: 1
Reputation: 2138
ArrayList! These are dynamic arrays very suitable for your use. Check them out: http://developer.android.com/reference/java/util/ArrayList.html
Upvotes: 5