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除外。
TOP