2017-10-18 3 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의 값을 변경하지만 아무것도 트리 맵에서 변경되지 않은 것입니다 .

+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