[Kaffe] I am getting a ConcurrentModificationException
Archie Cobbs
archie at whistle.com
Mon Sep 27 10:45:47 PDT 1999
Moses DeJong writes:
> I wrote a little test program to double check that what I was doing
> was correct. I was using the Hashtable.keys() method to iterate a
> table and remove each key like the following example.
>
> import java.util.*;
>
> public class HashTest {
> public static void main(String[] argv) {
> Hashtable h = new Hashtable();
> Enumeration search;
> String elem;
>
> h.put("one", new Integer(1));
> h.put("two", new Integer(2));
> h.put("three", new Integer(3));
>
> for (search = h.keys(); search.hasMoreElements() ; ) {
> elem = (String) search.nextElement();
>
> System.out.print("elem is \"" + elem + "\" value is " +
> h.get(elem) + " ... ");
> h.remove(elem);
> System.out.println("removed");
> }
> }
> }
FYI-
This works because the legacy routines (Hashtable.keys() and
Hashtable.elements()) take a "snapshot" of the hashtable (or
so it seems; this is not documented anywhere).
A more efficient way to do the above loop, using the Collections
framework, would be:
import java.util.*;
public class HashTest {
public static void main(String[] argv) {
Hashtable h = new Hashtable();
h.put("one", new Integer(1));
h.put("two", new Integer(2));
h.put("three", new Integer(3));
for (Iterator i = h.entrySet().iterator(); i.hasNext() ; ) {
Map.Entry entry = (Map.Entry)i.next();
Object key = entry.getKey();
Object value = entry.getValue();
System.out.print("key=" +key+ " value=" +value);
i.remove();
System.out.println(" removed");
}
}
}
This avoids two ineffiencies:
- Copying all of the keys into a separate list in Hashtable.keys()
- Looking up each value for every key
-Archie
___________________________________________________________________________
Archie Cobbs * Whistle Communications, Inc. * http://www.whistle.com
More information about the kaffe
mailing list