编辑
2025-06-12
JAVA代码工具
00
请注意,本文编写于 120 天前,最后修改于 24 天前,其中某些信息可能已经过时。
java
import java.util.HashMap; import java.util.Map; public class DualKeyMap<K1, K2, V> { private final Map<K1, V> map1 = new HashMap<>(); private final Map<K2, V> map2 = new HashMap<>(); private final Map<K1, K2> keyRelation = new HashMap<>(); private final Map<K2, K1> reverseKeyRelation = new HashMap<>(); public void put(K1 key1, K2 key2, V value) { map1.put(key1, value); map2.put(key2, value); keyRelation.put(key1, key2); reverseKeyRelation.put(key2, key1); } public V getByKey1(K1 key1) { return map1.get(key1); } public V getByKey2(K2 key2) { return map2.get(key2); } public K2 getKey2(K1 key1) { return keyRelation.get(key1); } public K1 getKey1(K2 key2) { return reverseKeyRelation.get(key2); } public static void main(String[] args) { DualKeyMap<String, Integer, String> map = new DualKeyMap<>(); map.put("A", 1, "Value1"); map.put("B", 2, "Value2"); System.out.println(map.getByKey1("A")); // 输出: Value1 System.out.println(map.getByKey2(2)); // 输出: Value2 System.out.println(map.getKey2("B")); // 输出: 2 System.out.println(map.getKey1(1)); // 输出: A } }

本文作者:tiger

本文链接:

版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!