2011-05-10 50 views
1

我在代碼中重複了以下幾個腳本幾次。我知道我可以運行一個函數來輕鬆完成這項工作,但是我可以像PHP中一樣使用變量作爲變量名稱。Java可變參數在變量名中使用

if (4val != null && 4val.length() > 0){ 
      Button 4 = new Button(this); 
      4.setText(4val); 
      4.setTextSize(20); 
     } 

我希望能夠像做

i=1; 
while{i > 10}{ 
    $$i = value; 
    //do stuff with $$i 
    i++; 
} 

在Java中這可能嗎?

+0

是您有意訪問到循環完成後的那些變量?爲什麼你不使用某種集合構造? – 2011-05-10 17:50:14

回答

3

使用Map代替

map.put("key","val");  
map.get("key"); 

那麼你也可以使用arrayList,但如果你使用HashMap您檢索過程就幾乎爲O(1)

+0

檢索過程幾乎是O(1)。與實際的數組相反,它實際上是O(1)嗎? – DJClayworth 2011-11-17 19:59:02

5

不,但您可以將按鈕粘在一個數組中,然後遍歷。

Button[] buttons = new Button[10]; 
// instantiate all the buttons 
for (int i = 0; i < buttons.length; i++) { 
    // update the button 
}