(Java newbie) Instantiating unknown number of objects
Java/OO newbie question:
main
instantiates Track
class. Now I want that object--track1
--to instantiate many Clip
objects, the number of which will not be known until runtime. From inside the Track
class I can make a new Clip
like this:
Clip clip1 = new Clip(); // this is track1.clip1 from main
But when I want to add more clips based on user input, how and where do I do this? From main
, something like:
Clip track1.clipX = new Clip();开发者_开发技巧
How do I name and reference Clip
objects when I don't know how many there will be?
You'd use a Collection (like a List or Set) to hold the multiple Clip objects:
int numberOfClips = 10;
List<Clip> clips = new ArrayList<Clip>();
for (int i = 0; i < numberOfClips; i++) {
Clip clip = new Clip();
clips.add(clip);
}
This would add 10 Clip objects to the array clips
. Instead of hardcoding to 10, you could set numberOfClips based on the user's input.
The List Java docs page describes all of the methods you can call on Lists, so that will show you how to get items in the List, remove items from the List, etc.
Why don't you use a List
to hold the clips in Track
?
public class Track {
...
List<Clip> clips;
void addClip(Clip clip) {
...
}
}
And something like that for the Clip
:
public class Clip {
private int index;
private String name;
...
}
And from the main
:
Track track = new Track();
Clip aClip = new Clip(1, "clip name");
track.addClip(aClip);
Clip anotherClip = new Clip(2, "another name");
track.addClip(anotherClip);
...
精彩评论