Linux 拨号vps windows公众号手机端

java的字典怎么创建和使用

lewis 9年前 (2016-12-10) 阅读数 9 #程序编程
文章标签 Java

在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。

版权声明

本文仅代表作者观点,不代表米安网络立场。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门