开发者

naming arrays in a loop

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[开发者_JAVA技巧]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


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...


You can make an array of arrays (sometimes called a multidimensional array):

int [][] arr = new int[137][42];


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).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜