Data structure for searching (different) Integers Java
I am looking for a data structure, optimized for search-operations (in the Java std-lib). I have to iterate over it several times, control eve开发者_StackOverflow中文版ry element and delete it in special cases. I have used a HashMap, but I always get following error:
for (Edge e : edges) {
if (special case)
edges.remove(e);
}
java.util.ConcurrentModificationException
at java.util.HashMap$HashIterator.nextEntry(HashMap.java:810)
at java.util.HashMap$KeyIterator.next(HashMap.java:845)
at package.name.TFinder.nN(TFinder.java:83)
at package.name.TFinder.fIT(TFinder.java:56)
at package.name.Main.main(Main.java:215)
From your description, you should be able to use HashMap
for this. The key is to use iterator.remove()
to delete entries:
for (Iterator<Map.Entry<Key,Value>> it = map.entrySet().iterator(); it.hasNext();)
{
Map.Entry<Key,Value> entry = it.next();
// process the entry
if(need to delete the entry)
{
it.remove();
}
}
That exception is thrown when you add/remove(/edit) something in a collection while you're terating through it (in e.g. a for loop).
To solve this, you would use a 'lock' in a multi-threaded environment. If you're doing stuff inside the responsible for-loop itself, you can consider copying your datastructure to a secondary (temporary) one, and then iterate on only one of the two and do all the necessary actions on the other.
Hope this helps!
Use ConcurrentHashMap
精彩评论