溫馨提示×

java怎么建立映射關系

小億
132
2023-12-12 03:57:37
欄目: 編程語言

在Java中,可以使用Map接口的實現類來建立映射關系。常用的Map實現類有HashMap、TreeMapLinkedHashMap。

以下是建立映射關系的一些常見操作:

  1. 創建一個Map對象:
Map<String, Integer> map = new HashMap<>();
  1. 添加鍵值對到映射中:
map.put("key1", 1);
map.put("key2", 2);
map.put("key3", 3);
  1. 從映射中獲取值:
int value1 = map.get("key1"); // 返回1
  1. 檢查映射中是否包含某個鍵:
boolean containsKey = map.containsKey("key1"); // 返回true
  1. 檢查映射中是否包含某個值:
boolean containsValue = map.containsValue(1); // 返回true
  1. 遍歷映射的鍵值對:
for (Map.Entry<String, Integer> entry : map.entrySet()) {
    String key = entry.getKey();
    Integer value = entry.getValue();
    System.out.println(key + " = " + value);
}
  1. 刪除映射中的鍵值對:
map.remove("key1");

請注意,Map接口允許鍵和值為null,但HashMapTreeMap不支持null鍵,LinkedHashMap除外。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女