0
有没有办法做到这一点? 我想打电话给使用它的一个字符串数组的名字试图使用名称的字符串来调用数组
public static void main(String [] args)
{
int [] temp=new int [1];
temp[0]=1;
String a="temp";
System.out.println(a[0]);
}
有没有办法做到这一点? 我想打电话给使用它的一个字符串数组的名字试图使用名称的字符串来调用数组
public static void main(String [] args)
{
int [] temp=new int [1];
temp[0]=1;
String a="temp";
System.out.println(a[0]);
}
NO,这是不可能的,因为变量名不能动态地在Java中声明。
尝试使用HashMap,它与您寻找的相似。
public static void main(String... args) {
HashMap<String, Integer> test = new HashMap<String, Integer>();
test.put("Temp", 1);
test.put("Temp2", 2);
System.out.println(test.get("Temp")); // returns one
HashMap<Integer, String> test2 = new HashMap<Integer, String>();
test2.put(1, "Temp");
test2.put(2, "Temp2");
System.out.println(test2.get(1)); // returns one
}
如果你想知道Map vs HashMap的区别,这是一个有趣的问题。
What is the difference between the HashMap and Map objects in Java?
这在Java中不可行,因为Java不是动态语言。这就是'Map <>'数据结构的用途。这也是[XY问题](http://xyproblem.info)的一个例子。如果你想解释你想完成的任务,我们可能会提供帮助,但是我们只能说这是一个简单的例子,“你不能用Java来做到这一点”。我建议你用一个有意义的例子来充实这个问题,否则风险就会降低。 –
同样的:[用Java中的动态名称分配变量](http://stackoverflow.com/questions/6729605/assigning-variables-with-dynamic-names-in-java)。 – azurefrog
[按字符串名称获取变量]的可能重复(http://stackoverflow.com/questions/13298823/get-variable-by-name-from-a-string) – fabian