2017-10-18 4 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 = 1からlastStatus = 0から値を変更しますが、何ものTreeMapに変更されないことです。

+0

「ツリーマップで何も変更されていません」とはどういう意味ですか?明らかに、値を変更するだけで、TreeMapのキーと順序は変更されません。 – Dabiuteef

+0

@Dabiuteef私は、TreeMap内のオブジェクト(値)を意味します。 TreeMap内のすべての値オブジェクトは、質問で提供されるforeachを使用して1にすべて変更しても、 '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

関連する問題