java在数组中获取元素但在字符串中知道arrayname

时间:2014-05-03 12:39:16

标签: java

String[] strsub0={"out","err","in","console()"};
String[] strsub1={"print","println","append","close","flush"};

我想获取数组元素,我知道数组的名称。但我知道字符串中的aray名称

int i=0; //this i get through a loop ,so i can't code strsub0 in my code.

String arrayname="strsub"+i;  //this is array name i want ,but it is a String.

//所以我想得到数组里面的所有元素,名字是strsub + i; //arrayname.length不返回strsub0.length,但我想要它。

for(int z=0;z<arrayname.length;z++){  

   System.out.println(arrayname[z]);

}

2 个答案:

答案 0 :(得分:2)

你想要一个数组数组。

String[][] strsub={{"out","err","in","console()"},
                   {"print","println","append","close","flush"};

然后你可以得到

String[] arr = strsub[i];

答案 1 :(得分:0)

您可以使用Map,其键是您想要的,其值是数组。如下所示:

Map<String, String[]> map = new HashMap<>(); //(assuming you have Java 7+ for the <> operator)
map.put("strsub0 ", new String[]{"out", "err", "in", "console()"});
map.put("strsub1 ", new String[]{"print", "println", "append", "close", "flush"});

然后检索以下值:map.get(arrayname)[i]。当然,您必须检查map.get(arrayname)是否确实存在或是null