java代码如何创建一个字典呢?
我们都知道字典是一个键和值一一对应的结构,那么java代码如何实现这一结构呢?
下文笔者将一一道来,如下所示
下文笔者将一一道来,如下所示
我们只需使用一个Map结构存储字典中的键和值
即可实现一个字典结构
例:字典定义和运用
HashMap<String, Integer> dictionary = new HashMap<>();
dictionary.put("apple", 1);
dictionary.put("banana", 2);
dictionary.put("orange", 3);
//从字典中获取值
int appleValue = dictionary.get("apple");
System.out.println("The value of 'apple' is: " + appleValue);
//遍历字典中的所有键值对
for (Map.Entry<String, Integer> entry : dictionary.entrySet()) {
System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
}
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


