溫馨提示×

java的字典怎么創建和使用

小億
226
2024-03-04 17:19:57
欄目: 編程語言

在Java中,可以使用HashMap來創建字典,也稱為映射或鍵值對。以下是創建和使用字典的示例:

  1. 創建一個HashMap對象來表示字典:
HashMap<String, Integer> dictionary = new HashMap<>();

在這個例子中,字典的鍵是String類型,值是Integer類型。

  1. 向字典中添加鍵值對:
dictionary.put("apple", 1);
dictionary.put("banana", 2);
dictionary.put("orange", 3);
  1. 從字典中獲取值:
int appleValue = dictionary.get("apple");
System.out.println("The value of 'apple' is: " + appleValue);
  1. 遍歷字典中的所有鍵值對:
for (Map.Entry<String, Integer> entry : dictionary.entrySet()) {
    System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
}

這樣就可以創建一個字典并使用它來存儲和檢索鍵值對。請記住,在Java中,HashMap是一種無序的數據結構,如果需要有序的字典,可以使用TreeMap。

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