So, simple question that seems to be baffling me. I have a series of ArrayList because they need to be expandable. Now, I would like to be able to pull the nth object from each one with a simple for loop.
public ArrayList<String> name = new ArrayList<String>();
public ArrayList<Integer> stamina = new ArrayList<Integer>();
public ArrayList<Integer> heart = new ArrayList<Integer>();
public ArrayList<Integer> intel = new ArrayList<Integer>();
public ArrayList<Integer> speed = new ArrayList<Integer>();
I'll be adding/pulling information from these later in my code, so I would like it to be easily accessible via a single 2D array. With something like,
racerInfo[][] = { name, stamina, heart, intel, speed };
Then if I want information for, say, racer number 7
for ( int i=0; i<=racerInfo.length - 1; i++ ) {
System.out.println(racerInfo[i][7]);
}
How would I go about setting up the racerInfo field? I can't seem to figure out the right setup. If you have any better suggestions for the rest I am completely open as I am still very new to this and just attempting to cobble something together that works.
2 Answers 2
Your approach is a bit primitive, and you wouldn't have this problem if you had a better architecture.
Instead of having a bunch of lists of racer properties, you should create a racer class with the properties.
class Racer {
private String name;
private int stamina;
...
public Racer(String name) {
this.stamina = Math.random(...);
...
}
public function getStamina() {
return this.stamina;
}
}
Then you instantiate all your racers
Racer racer1 = new Racer("Alice");
and put them in a single list (or possibly a map) of racers:
List<Racer> racers = new ArrayList<Racer>();
racers.add(racer1);
or you could add them directly without first assigning them to a variable
racers.add(new Racer("Bob"));
6 Comments
racers.add(new Racer(someString, someInt, ...))Math.random() to generate the stats for a racer. I know how I would add it to the list you've indicated, but how would I then pull the stats for display/implementation later? Like. I'm not sure what is storing the info or where it is being stored.make racerInfo an arrayList of arrayLists, something like this
ArrayList<ArrayList> racerInfo = new ArrayList<ArrayList>(Arrays.asList(new ArrayList[]{name, stamina, heart, intel, speed}));
RacerInfoinstead of an array of lists. Also - a bit nit-picky - Try to create collections against their interfaces, not there implementations (List list = new ArrayList())