溫馨提示×

java如何定義字典

小億
130
2024-08-17 13:09:36
欄目: 編程語言

在Java中,可以使用Map來定義字典,Map是一種鍵值對的集合,可以存儲多個鍵值對,每個鍵值對包含一個鍵和對應的值。常用的Map實現類包括HashMap、TreeMap、LinkedHashMap等。

以下是一個使用HashMap來定義字典的示例代碼:

import java.util.HashMap;
import java.util.Map;

public class Dictionary {
    public static void main(String[] args) {
        // 定義一個字典
        Map<String, String> dictionary = new HashMap<>();
        
        // 向字典中添加鍵值對
        dictionary.put("apple", "蘋果");
        dictionary.put("banana", "香蕉");
        dictionary.put("orange", "橙子");
        
        // 獲取字典中的值
        String chineseApple = dictionary.get("apple");
        System.out.println("apple的中文意思是:" + chineseApple);
        
        // 遍歷字典中的所有鍵值對
        for (Map.Entry<String, String> entry : dictionary.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();
            System.out.println(key + "的中文意思是:" + value);
        }
    }
}

在上面的示例中,我們使用HashMap來定義一個字典,并向字典中添加了一些鍵值對。通過get方法可以根據鍵獲取對應的值,通過entrySet方法可以遍歷字典中的所有鍵值對。

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