[英]How do I iterate over (and make changes to) a collection that is the value of another collection
I have a map that maps bytes to sets of bytes. 我有一个将字节映射到字节集的映射。 I want to walk through the map and make changes to the set.
我想遍历地图并对设置进行更改。
private HashMap<Byte, HashSet<Byte>> table;
...
Iterator<Entry<Byte, HashSet<Byte>>> it = table.entrySet().iterator();
while( it.hasNext() ) {
Map.Entry<Byte, HashSet<Byte>> pairs = it.next();
byte node = pairs.getKey();
HashSet<Byte> hSet = pairs.getValue();
Iterator<Byte> setIter = hSet.iterator();
while( setIter.hasNext() ) {
byte sNode = setIter.next(); // Throws a ConcurrentModificationException
...
}
}
This code throws a ConcurrentModificationException when I try to iterate through the sub iterator. 当我尝试遍历子迭代器时,此代码将引发ConcurrentModificationException。 What should I do to iterate through, and make changes to, this collection within my map?
我应该怎么做才能遍历地图中的这个集合并对其进行更改?
Try something like that : 试试这样的事情:
for(Byte node : table.keySet()) {
HashSet<Byte> hSet = table.get(node);
Iterator<Byte> setIter = hSet.iterator();
while( setIter.hasNext() ) {
byte sNode = setIter.next();
...
}
}
If you want to modify the hSet
your best approach might be to loop over a copy of the Set
: 如果要修改
hSet
最好的方法可能是遍历Set
的副本:
for(Byte node : table.keySet()) {
HashSet<Byte> hSet = table.get(node);
for (Byte sNode : new HashSet<Byte>(hSet)) {
//do things which modifies the original hSet
}
}
I think you get the exception because you modify the set during the iteration (in the lines that were not included into the question). 我认为您之所以会得到例外,是因为您在迭代过程中修改了集合(在问题未包括的行中)。 The "fail-fast" iterators are throwing it, if they detect that the structure of the collection has been changed.
如果“快速失败”迭代器检测到集合的结构已更改,则会将其抛出。
Note that this exception does not always indicate that an object has been concurrently modified by a different thread.
请注意,此异常并不总是表示对象已被其他线程同时修改。 If a single thread issues a sequence of method invocations that violates the contract of an object, the object may throw this exception.
如果单个线程发出违反对象约定的方法调用序列,则该对象可能会抛出此异常。 For example, if a thread modifies a collection directly while it is iterating over the collection with a fail-fast iterator, the iterator will throw this exception.
例如,如果线程在使用快速失败迭代器迭代集合时直接修改了集合,则迭代器将抛出此异常。
http://docs.oracle.com/javase/7/docs/api/java/util/ConcurrentModificationException.html http://docs.oracle.com/javase/7/docs/api/java/util/ConcurrentModificationException.html
If you are only deleting from the set while you iterate it, you can use the remove method of the iterator instead of the Set methods. 如果仅在迭代时从集合中删除,则可以使用迭代器的remove方法而不是Set方法。 If you also want to add to the set while iterating, you need to create a copy of the Set, and iterate that (but this case is unlikely, you can add to a set without iterating it...)
如果您还想在迭代时添加到集合中,则需要创建集合的副本并对其进行迭代(但是这种情况不太可能,您可以在不迭代的情况下添加到集合中...)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.