Reputation: 92
i'm out of my league.
ok so if i can do this:
int[]teams = new int[3];
for (int i = 0; i < 3; i++)
{
teams[i] = i;
}
how do i do the similar thing but naming multiple arrays, ie
for (int i = 0; i < 3; i++)
{
int[]i = new int[3];
}
I have read you can't name an array with a variable so I can't just see how to produce arrays with different names (basically more than one) using a loop.
Thanks
Upvotes: 2
Views: 8177
Reputation: 15029
You cannot dynamically generate variable names, but you can achieve the same effect with a Map:
//Store mappings from array name (String) to int arrays (int[])
Map<String, int[]> namedArrays = new HashMap<String, int[]>();
for (int i = 0; i < 3; i++)
{
//This is going to be the name of your new array
String arrayName = String.valueOf(i);
//Map an new int[] to this name
namedArrays.put(arrayName, new int[3]);
}
//If you need to access array called "2" do
int[] array2 = namedArrays.get("2")
The advantage of doing it this way is that you can have multiple arrays with same names as long as they are in different maps. But note that when you map two or more arrays to the same name in the same map, the previous array will be overriden (lost).
Upvotes: 1
Reputation: 35970
You'd do the following (Java):
int teams[][] = new teams[3][3]
You'd do the following (C++):
int** teams = new int*[3];
for(int i=0; i<3; i++){
teams[i] = new int[3];
}
or you could just do
int teams[3][3];
for(int i=0; i<3; i++){
for(int j=0; j<3; j++){
teams[i][j] = //whatever you want
}
}
Edit in response to your comment below:
What you're looking for is a MultiMap. There you're going to get:
MultiMap foo = new MultiMap();
foo.put("Bob", 1);
foo.put("Bob", 2);
etc...
Upvotes: 3
Reputation: 372684
You can make an array of arrays (sometimes called a multidimensional array):
int [][] arr = new int[137][42];
Upvotes: 2