【发布时间】:2018-11-11 01:54:21
【问题描述】:
我在 for 循环开始的那一行收到了 java.util.ConcurrentModificationException(参见代码中的注释)。
为什么我在这个 unmodifiableSet 上得到 ConcurrentModificationException?
final Set<Port> portSet = Collections.unmodifiableSet(node.getOpenPorts());
if (!portSet.isEmpty()) {
StringBuilder tmpSb = new StringBuilder();
for (Port pp : portSet) { // <------- exception happening here
tmpSb.append(pp.getNum()).append(" ");
}
}
我从未见过这种情况,但我收到了来自 Google 的崩溃报告。
【问题讨论】:
-
node.getOpenPorts()返回的Set可以被其他代码(不一定是你自己的代码)修改吗? -
好的。我想我对
Collections.unmodifiableSet复制该集合的假设是错误的。我猜它只是包装并防止添加/删除? -
是的,
Collections.unmodifiableXXX方法都包装了给定的集合。这些包装器委托给底层集合进行读取操作,但抛出UnsupportedOperationException进行写入操作。
标签: java android concurrency