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?
The closest you will get in Java is: Map<String, String[]> map = new HashMap<String, String[]>(); for (int k=0; k=5; k++){ map. put(Integer. toString(k), new String[3]); } // now map.
Objects/Variables: Java Naming convention specifies that instances and other variables must start with lowercase and if there are multiple words in the name, then you need to use Uppercase for starting letters for the words except for the starting word.
You can create custom dynamic objects by using the classes in the System. Dynamic namespace. For example, you can create an ExpandoObject and specify the members of that object at run time. You can also create your own type that inherits the DynamicObject class.
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:
List<String[]> kList = new ArrayList<String[]>();
for(int k = 0; k < 5; k++){
kList.add(new String[3]);
}
Or perhaps a little closer to what you're after, you can use a Map:
Map<Integer,String[]> kMap = new HashMap<Integer,String[]>();
for(int k = 0; k < 5; k++){
kMap.put(k, new String[3]);
}
// access using kMap.get(0) etc..
Others have already provided great answers, but just to cover all bases, Java does have array of arrays.
String[][] k = new String[5][3];
k[2][1] = "Hi!";
Now you don't have 5 variables named k1
, k2
, k3
, k4
, k5
, each being a String[3]
...
...but you do have an array of String[]
, k[0]
, k[1]
, k[2]
, k[3]
, k[4]
, each being a String[3]
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With