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