2015-12-31 34 views
3

從一個內部類中引用的局部變量必須是最終或有效地在下面的代碼所示的最終錯誤:無法訪問內部類問題Java的

public Vector<Map<String, Object>> newsFeedConnection(String var, Hashtable punishment) { 
    ConnectionRequest connectionRequest; 
    connectionRequest = new ConnectionRequest() { 
     @Override 
     protected void readResponse(InputStream input) throws IOException { 
      JSONParser p = new JSONParser(); 
      results = p.parse(new InputStreamReader(input)); 

      punishment = (Hashtable) results.get("punishment"); 
     } 
    } 
} 

但是,當我改變它變成最後的(下面的代碼),它再次給出「不能給最終變量處罰分配一個值」的錯誤。

public Vector<Map<String, Object>> newsFeedConnection(String var, final Hashtable punishment) { 
    ConnectionRequest connectionRequest; 
    connectionRequest = new ConnectionRequest() { 
     @Override 
     protected void readResponse(InputStream input) throws IOException { 
      JSONParser p = new JSONParser(); 
      results = p.parse(new InputStreamReader(input)); 

      punishment = (Hashtable) results.get("punishment"); 
     } 
    } 
} 

我該如何解決這個問題?如果我設置了一個全局變量,我無法從其他類中的方法訪問該值。

+0

'懲罰'必須是'最終',但由於您無法更改'參數'的引用,它實際上是沒有意義的 – MadProgrammer

+0

這是我確切的問題,如果我改變它到最後我不能指定一個值,這是什麼我需要去做。 –

+1

您可能還會發現'punishment.putAll((Hashtable)results.get(「懲罰」))''可能會工作得更好,但是這裏假定'ConnectionRequest'是一個阻塞方法調用 – MadProgrammer

回答

0

按值傳遞與按引用傳遞 - 當傳遞對象引用時,您正在通過引用傳遞。當你這樣做時,你可以通過在對象上調用適當的方法來改變對象的狀態,但是你不能改變對象本身的引用。例如:

public class TestPassByReference { 

    public static void main(String[] args){ 
     StringBuilder stringBuilder = new StringBuilder("Lets Test!"); 
     changeStringDoesNotWork(stringBuilder); 
     System.out.println(stringBuilder.toString()); 
     changeString(stringBuilder); 
     System.out.println(stringBuilder.toString()); 
    } 

    static void changeString(StringBuilder stringBuilder){ 
     stringBuilder.append(" Yeah I did it!"); 
    } 

    static void changeStringDoesNotWork(StringBuilder stringBuilder){ 
     stringBuilder = new StringBuilder("This will not work!"); 
    } 
} 

輸出:

Lets Test!    //Value did not change 
Lets Test! Yeah I did it! 

現在我希望你能合作涉及你正在嘗試做這個基本方面,因此不正確的衝突。

什麼但是你可以做到這一點:

HashTable tempHashTable = (Hashtable) results.get("punishment");  
punishment.clear(); 
punishment.putAll(tempHashTable); 

而且爲什麼要使用哈希表?那裏有更好的線程安全的集合類可以提供更好的性能。

0

您可以通過更新您punishment變量解決這個問題:

public Vector<Map<String, Object>> newsFeedConnection(String var, final Hashtable punishment) { 
     ConnectionRequest connectionRequest; 
     connectionRequest = new ConnectionRequest() { 
      @Override 
      protected void readResponse(InputStream input) throws IOException { 
       JSONParser p = new JSONParser(); 
       results = p.parse(new InputStreamReader(input)); 

       punishment.putAll((Hashtable) results.get("punishment")); 
        } 
      } 
     } 
} 
2

您重新發起最後的變量,它的概念不能接受,只是改變裏面的懲罰值,而無需重新創建它,這將解決您的問題。