修复特定情况下BiMap覆盖Value后,仍能通过旧Value查询到Key问题

This commit is contained in:
Looly 2023-10-18 08:57:36 +08:00
parent bc30ecc3ef
commit 3f9c9c6252
3 changed files with 39 additions and 4 deletions

View File

@ -42,7 +42,13 @@ public class BiMap<K, V> extends MapWrapper<K, V> {
@Override
public V put(final K key, final V value) {
final V oldValue = super.put(key, value);
if (null != this.inverse) {
if(null != oldValue){
// issue#I88R5M
// 如果put的key相同value不同需要在inverse中移除旧的关联
this.inverse.remove(oldValue);
}
this.inverse.put(value, key);
}
return super.put(key, value);

View File

@ -25,8 +25,8 @@ public class BiMapTest {
biMap.put("aaa", 111);
biMap.put("bbb", 222);
Assertions.assertEquals(new Integer(111), biMap.get("aaa"));
Assertions.assertEquals(new Integer(222), biMap.get("bbb"));
Assertions.assertEquals(Integer.valueOf(111), biMap.get("aaa"));
Assertions.assertEquals(Integer.valueOf(222), biMap.get("bbb"));
Assertions.assertEquals("aaa", biMap.getKey(111));
Assertions.assertEquals("bbb", biMap.getKey(222));
@ -39,7 +39,7 @@ public class BiMapTest {
biMap.put("bbb", 222);
biMap.computeIfAbsent("ccc", s -> 333);
Assertions.assertEquals(new Integer(333), biMap.get("ccc"));
Assertions.assertEquals(Integer.valueOf(333), biMap.get("ccc"));
Assertions.assertEquals("ccc", biMap.getKey(333));
}
@ -50,7 +50,7 @@ public class BiMapTest {
biMap.put("bbb", 222);
biMap.putIfAbsent("ccc", 333);
Assertions.assertEquals(new Integer(333), biMap.get("ccc"));
Assertions.assertEquals(Integer.valueOf(333), biMap.get("ccc"));
Assertions.assertEquals("ccc", biMap.getKey(333));
}
}

View File

@ -0,0 +1,29 @@
/*
* Copyright (c) 2023. looly(loolly@aliyun.com)
* Hutool is licensed under Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
* https://license.coscl.org.cn/MulanPSL2
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
package org.dromara.hutool.core.map;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import java.util.LinkedHashMap;
public class IssueI88R5MTest {
@Test
void biMapTest() {
final BiMap<String, Integer> biMap = new BiMap<>(new LinkedHashMap<>());
biMap.put("aaa", 111);
biMap.getKey(111);
biMap.put("aaa", 222);
Assertions.assertNull(biMap.getKey(111));
}
}