gpt4 book ai didi

java - ConcurrentHashMap - 奇怪的行为

转载 作者:行者123 更新时间:2023-12-03 16:00:16 25 4
gpt4 key购买 nike

谁能告诉我这段代码出了什么问题?我要拔头发了!

如果我使用 HashMap 而不是 ConcurrentHashMap 则没有任何问题。代码使用JDK 5.0编译

public class MapTest {
public Map<DummyKey, DummyValue> testMap = new ConcurrentHashMap<DummyKey, DummyValue>();

public MapTest() {
DummyKey k1 = new DummyKey("A");
DummyValue v1 = new DummyValue("1");
DummyKey k2 = new DummyKey("B");
DummyValue v2 = new DummyValue("2");

testMap.put(k1, v1);
testMap.put(k2, v2);
}

public void printMap() {
for(DummyKey key : testMap.keySet()){
System.out.println(key.getKeyName());
DummyValue val = testMap.get(key);
System.out.println(val.getValue());
}
}

public static void main(String[] args){
MapTest main = new MapTest();
main.printMap();
}


private static class DummyKey {
private String keyName = "";

public DummyKey(String keyName){
this.keyName = keyName;
}

public String getKeyName() {
return keyName;
}

@Override
public int hashCode() {
return keyName.hashCode();
}

@Override
public boolean equals(Object o) {
return keyName.equals(o);
}
}

private static class DummyValue {
private String value = "";

public DummyValue(String value){
this.value = value;
}

public String getValue() {
return value;
}
}
}

这是输出:

B
Exception in thread "main" java.lang.NullPointerException
at test.MapTest.printMap(MapTest.java:27)
at test.MapTest.main(MapTest.java:34)

最佳答案

DummyKey.equals 方法实现不正确,因为 testMap.get(key) 总是返回 null。试试这个

public boolean equals(Object o) {
if (o instanceof DummyKey) {
DummyKey other = (DummyKey) o;
return keyName == null ? other.keyName == null : keyName.equals(other.keyName);
}
return false;
}

hashCode 也需要一点改动来和 equals 保持一致

public int hashCode() {
return keyName == null ? 0 : keyName.hashCode();
}

关于java - ConcurrentHashMap - 奇怪的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17565644/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com