2017-10-18 43 views
0

所以我有一個TreeMap<Integer, Transmitter>,並通過一個foreach,我試圖修改發射器的內部屬性,但它感覺它是在TreeMap中製作對象的副本,因爲它不會更改TreeMap中的值。TreeMap foreach不改變值對象

我的foreach代碼:

 for (TreeMap<Integer, Transmitter> current : transmitterDiagnosticMap.values()) { 
      for (Transmitter t : current.values()) { 
       String transmitterError = t.printErrorReport(date, appContext); 
       if (transmitterError != null) 
        stringsErrorsAndWarnings.add(transmitterError); 
      } 
     } 

我printErrorReport代碼:

 public String printErrorReport(String data, Context context) { 
     String output = null; 
     if (this.writeOnReport()) { // This is the function that will modify the object 
      output = data + " - " + this.getTension(); 
     } 
     return output; 
    } 
    // This is the method that tells whether or not the report will be written, and changes the variable lastStatus if necessary 
    private boolean writeOnReport() { 
     if (this.status > 0) { 
      if (this.lastStatus == 0 || this.lastStatus != this.status) { 
       this.lastStatus = this.status; 
       return true; 
      } 
      return false; 
     } else { 
      this.lastStatus = 0; 
      return false; 
     } 
    } 

什麼我能看到的是,Transmitter t實際上改變從lastStatus = 0lastStatus = 1價值,但沒有什麼是樹形圖改變。

+0

你是什麼意思,說「沒有什麼改變的TreeMap」?顯然,如果你只是改變這個值,那麼TreeMap的鍵和順序就不會改變。 – Dabiuteef

+0

@Dabiuteef我的意思是TreeMap中的對象(值)。即使我使用問題中提供的foreach將它們全部更改爲1,TreeMap中的所有值對象都保留爲'lastStatus = 0'。 – Lukingan

回答

2

您必須使用迭代器來更改TreeMap中的值。使用current.values()將創建副本而不是變更對象。

您需要迭代TreeMap的鍵並更新值。

for (TreeMap<Integer, Transmitter> current : transmitterDiagnosticMap.values()) { 
    for (Map.Entry<Integer, Transmitter> entry : current.entrySet()) { 
     Transmitter t = entry.getValue(); 
     String transmitterError = t.printErrorReport(date, appContext); 
     if (transmitterError != null) 
      stringsErrorsAndWarnings.add(transmitterError); 
     entry.setValue(t); 
    } 
} 
+0

非常感謝,Anoop。這就像一個魅力。 – Lukingan