Let's say I needed to make a series of String[] objects.
I know that if i wanted to make a string array called "test" to hold 3 Strings I could do
String[] test = new String[3];
But let's say I needed to make a series of these arrays and I wanted them to be named, 1,2, 3, 4, 5... etc. For however many I needed and I didn't know how many I'd need.
How do I achieve a similar effect to this:
for (int k=0; k=5; k++){
String[] k = new String[3];
}
Which would created 5 string arrays named 1 through 5. Basically I want to be able to create array objects with a name detemined by some other function. Why can't I seem to do this? Am I just being stupid?
Others have already provided great answers, but just to cover all bases, Java does have array of arrays.
Now you don't have 5 variables named
k1
,k2
,k3
,k4
,k5
, each being aString[3]
......but you do have an array of
String[]
,k[0]
,k[1]
,k[2]
,k[3]
,k[4]
, each being aString[3]
.The closest you will get in Java is:
Note that
"3"
is not a variable, but in conjunction with themap
object it works like one ... sort of.There aren't any "variable variables" (that is variables with variable names) in Java, but you can create Maps or Arrays to deal with your particular issue. When you encounter an issue that makes you think "I need my variables to change names dynamically" you should try and think "associative array". In Java, you get associative arrays using
Map
s.That is, you can keep a List of your arrays, something like:
Or perhaps a little closer to what you're after, you can use a Map:
What you want to do is called metaprogramming - programming a program, which Java does not support (it allows metadata only through annotations). However, for such an easy use case, you can create a method which will take an int and return the string array you wanted, e.g. by acccessing the array of arrays. If you wanted some more complex naming convention, consider swtich statement for few values and map for more values. For fixed number of values with custom names define an Enum, which can be passed as an argument.