How do I dynamically name objects in Java?

2020-02-25 08:23发布

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?

4条回答
\"骚年 ilove
2楼-- · 2020-02-25 08:35

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

查看更多
祖国的老花朵
3楼-- · 2020-02-25 08:37

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.get("3") will get the string array named "3".

Note that "3" is not a variable, but in conjunction with the map object it works like one ... sort of.

查看更多
虎瘦雄心在
4楼-- · 2020-02-25 08:39

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

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..
查看更多
爷的心禁止访问
5楼-- · 2020-02-25 08:52

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.

查看更多
登录 后发表回答