相比
synchronized (countList) {
while (iter.hasNext()) {
Entry<Long, Long> entry = iter.next();
if(entry.getVaue>0)
entry.output();
}
countList.clear();
}
Run Code Online (Sandbox Code Playgroud)
同
synchronized (countList) {
while (iter.hasNext()) {
Entry<Long, Long> entry = iter.next();
if(entry.getVaue>0)
entry.output();
iter.remove();
}
}
Run Code Online (Sandbox Code Playgroud)
有真正的区别吗?我猜测垃圾收集可能对collection.clear方法更好.
pol*_*nts 12
在某些情况下,N remove()通过迭代器会产生O(N log N)甚至更糟的O(N^2)性能(例如,在a上ArrayList).我想不出任何clear()可能表现糟糕的情况.
我想说这clear()可能更好.它是作为一个操作完成的,因此实现可以更好地优化它,因为它不是对集合的增量修改remove()(需要维护不变量等).
此外,集合迭代器必须防范IllegalStateException和/或ConcurrentModificationException.用N remove()s,这是N检查,可以加起来.最后,作为提醒,并非所有迭代器都支持remove().
想一想:
remove()操作是通过中间人(迭代器)完成的,它在集合N变空之前将其置于不同的状态clear()是对集合的直接操作,它只有1个状态转换| 归档时间: |
|
| 查看次数: |
143 次 |
| 最近记录: |