java怎么建立映射关系
在Java中,可以使用Map
接口的实现类来建立映射关系。常用的Map
实现类有HashMap
、TreeMap
和LinkedHashMap
。
以下是建立映射关系的一些常见操作:
创建一个Map
对象:
Map<String, Integer> map = new HashMap<>();
添加键值对到映射中:
map.put("key1", 1);
map.put("key2", 2);
map.put("key3", 3);
从映射中获取值:
int value1 = map.get("key1"); // 返回1
检查映射中是否包含某个键:
boolean containsKey = map.containsKey("key1"); // 返回true
检查映射中是否包含某个值:
boolean containsValue = map.containsValue(1); // 返回true
遍历映射的键值对:
for (Map.Entry<String, Integer> entry : map.entrySet()) {
String key = entry.getKey();
Integer value = entry.getValue();
System.out.println(key + " = " + value);
}
删除映射中的键值对:
map.remove("key1");
请注意,Map
接口允许键和值为null
,但HashMap
和TreeMap
不支持null
键,LinkedHashMap
除外。
阅读剩余
THE END