Reputation: 84
So I have a TreeMap<Integer, Transmitter>
and through a foreach I am trying to modify an inner attribute of the transmitter, but it feels like it is making a copy of the object in the TreeMap, since it does not change the value in the TreeMap.
My foreach code:
for (TreeMap<Integer, Transmitter> current : transmitterDiagnosticMap.values()) {
for (Transmitter t : current.values()) {
String transmitterError = t.printErrorReport(date, appContext);
if (transmitterError != null)
stringsErrorsAndWarnings.add(transmitterError);
}
}
My printErrorReport code:
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;
}
}
What I could notice is that the Transmitter t
actually changes the value from lastStatus = 0
to lastStatus = 1
, but nothing is changed in the TreeMap.
Upvotes: 0
Views: 473
Reputation: 5720
You have to use the iterator to mutate the values in the TreeMap. Using current.values()
will create a copy instead of mutating the object.
You need to iterate over the keys of the TreeMap and update the values.
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);
}
}
Upvotes: 2