如何动态地命名Java对象? [英] How do I dynamically name objects in Java?

查看:800
本文介绍了如何动态地命名Java对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比方说,我需要做出一系列的String []的对象。

Let's say I needed to make a series of String[] objects.

我知道,如果我想创建一个名为测试字符串数组来保存3串我可以做

I know that if i wanted to make a string array called "test" to hold 3 Strings I could do

的String [] =测试新的String [3];

String[] test = new String[3];

但是,让我们说,我需要做出一系列的这些阵列的,我想他们被命名,1,2,3,4,5 ...等。然而,许多我需要的,我不知道有多少我所需要的。

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];
}

这将创建一个名为5 1字符串数组至5

基本上,我希望能够与其他一些功能detemined的名称创建数组对象。为什么我不能似乎做到这一点?我只是愚蠢?

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?

推荐答案

有没有任何变量变量(即变量名变量)在Java中,但您可以创建地图或阵列处理您的特定问题。当你遇到你认为的问题,使我需要我的变量动态地更改名称你应该尝试并认为关联数组。在Java中,您使用地图取值得到关联数组。

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

这篇关于如何动态地命名Java对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆