-
Bug
-
Resolution: Fixed
-
P4
-
1.2.2
-
beta
-
generic
-
generic
-
Verified
Name: stC104175 Date: 04/07/2000
java version "1.2.2"
Classic VM (build JDK-1.2.2-001, green threads, sunwjit)
Bug when subclassing AbstractMap with a Cloneable class
It is impossible to extend AbstractMap and be Cloneable, because of
this design bug:
(a) AbstractMap keeps private cached state (required for keySet() and values())
(b) AbstractMap does not override clone() nor implement Cloneable
The combination of facts (a) and (b) lead inevitably to the bug
exhibited by the following program, which incorrectly prints "true"
instead of "false".
import java.util.*;
public class AMapBug extends AbstractMap implements Cloneable {
private HashMap map = new HashMap();
public Set entrySet() {
return map.entrySet();
}
public Object put(Object key, Object value) {
return map.put(key, value);
}
public Object clone() {
AMapBug clone;
try {
clone = (AMapBug)super.clone();
} catch (CloneNotSupportedException e) {
clone = null; // can't happen
}
clone.map = (HashMap)map.clone();
return clone;
}
public static void main(String[] args) throws Exception {
AMapBug t1 = new AMapBug();
t1.put("key1", "value1");
Set t1keys = t1.keySet();
AMapBug t2 = (AMapBug)t1.clone();
t2.put("key2", "value2");
Set t2keys = t2.keySet();
System.out.println(t1keys.equals(t2keys));
}
}
The simple solution is to properly implement clone() in AbstractMap.
(Review ID: 103395)
======================================================================