3

I am wondering if there is a way to create arrays in java based on a variable amount. So if I needed to create 10 arrays a loop would make 10(all named sequentially). But if I did not need 10 arrays the loop would create and many as needed.

I am envisioning something like this:

for(i=0 up to i=imax)

create arrayi

where i is the variable in the for loop.

If imax is set to 3 it would produce: array0,array1,array2,array3

thanks.

1
  • Please precise what these arrays should contain and how big they should be. Commented Jun 3, 2011 at 21:33

3 Answers 3

7

Yes; you can create an array of arrays. Let's say that you want arrays of int:

int numberOfArrays = 10;
int[][] arrays = new int[numberOfArrays][];
for (int i = 0; i < numberOfArrays; i++)
    arrays[i] = new int[x]; // Where x is the size you want array i to be

However, you can not dynamically create variables called array0, array1, and so on. With multidimensional arrays, there is no need for such a collection of variables, because you can rather write arrays[0], arrays[1]; this is more flexible as well, since you can index into the array collection with arrays[i], which you couldn't do if you had array0, array1, and so on.

Sign up to request clarification or add additional context in comments.

2 Comments

Yeah, the thing that would be most similar to the wanted solution would be using a Hashmap<String, Integer[]>
Fantastic! This is definitely what I will be using. I have had this questions knocking around in my head for a while but your implementation is much easier and works better.
0

No chance to do this, you have to take the twodimensional array approach...

Comments

0

Java doesn't allow this sort of meta-programming. You cannot programmatically declare variables.

As @Aasmund writes, what you can do is declare an array to hold your arrays.

For your specific question, this is what the result would like:

String[][] array = new String[IMAX][];
for (int i = 0; i < array.length; ++i) {
  array[i] = createArray(...);
}

// cannot use 'array2', but something close:
String[] contents = array[2];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.