除了线程问题之外,还有一个明确的途径来实现这个结果:
class Key implements CharSequence {
private byte[] key;
public Key(String key) {
// Take a copy of the bytes of the string.
this.key = key.getBytes();
}
@Override
public int length() {
return key.length;
}
@Override
public char charAt(int index) {
return (char) key[index];
}
@Override
public CharSequence subSequence(int start, int end) {
return new Key(new String(key).substring(start, end));
}
// Allow the key to change.
public void setKey(String newValue) {
key = newValue.getBytes();
}
@Override
public String toString() {
return new String(key);
}
}
public void test() {
Map<CharSequence, String> testMap = new HashMap<>();
Key aKey = new Key("a");
Key bKey = new Key("b");
testMap.put(aKey, "a");
testMap.put(bKey, "b");
bKey.setKey("a");
System.out.println(testMap.keySet());
}
这实质上是使地图的键可变,因此可以在将它们添加到地图后对其进行更改。
尽管这可能不是您面临的问题(多线程问题更有可能),但这是对我的 HashMap 为何有重复键的问题的真正答案?.