TreeMap foreach不会更改值对象

时间:2017-10-18 18:04:36

标签: java android treemap

所以我有一个TreeMap<Integer, Transmitter>并通过foreach我试图修改发送器的内部属性,但感觉它是在TreeMap中制作对象的副本,因为它不会改变TreeMap中的值。

我的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 = 0更改为lastStatus = 1,但TreeMap中没有任何更改。

1 个答案:

答案 0 :(得分: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);
    }
}