スレッドの問題とは別に、この結果への明確なルートがあります。
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 に重複したキーがあるのはなぜですか?」という質問に対する本当の答えです。.