创建 HashMap 并添加键值对的 Java 程序
在本文中,我们将编写一个 Java 程序来创建 HashMap 并添加键值对。我们将使用 HashMap 类,我们可以从 java.util 包 中导入 **HashMap 类**。
**HashMap** 是一种以键值对形式存储数据的集合,允许根据键快速检索值。在给定的程序中,我们还将了解如何使用迭代器显示存储在 HashMap 中的元素。
问题陈述
用 Java 编写一个程序来创建 HashMap 并添加键值对 -
输出
Belt: 600
Wallet: 700
Bag: 1100
创建 HashMap 并添加键值对的步骤
以下是创建 HashMap 并添加键值对的步骤 -
- 首先导入必要的包 **java.util.*** 以使用 **HashMap**、Set 和 **Iterator**。
- 实例化一个 **HashMap** 对象以存储键值对。
- 使用 put() 方法 添加键值对,以将项目添加到 HashMap 中。
- 为了获取条目集,我们将使用 entrySet() 方法。
- 使用带有 while 循环 的迭代器遍历条目并打印每个键值对。
创建 HashMap 并添加键值对的 Java 程序
以下是如何创建 HashMap 并添加键值对的示例 -
import java.util.*;
public class Demo {
public static void main(String args[]) {
// Create a hash map
HashMap<String, Integer> hm = new HashMap<>();
// Put elements to the map
hm.put("Bag", 1100);
hm.put("Wallet", 700);
hm.put("Belt", 600);
// Get a set of the entries
Set<Map.Entry<String, Integer>> set = hm.entrySet();
// Get an iterator
Iterator<Map.Entry<String, Integer>> i = set.iterator();
// Display elements
while(i.hasNext()) {
Map.Entry<String, Integer> me = i.next();
System.out.print(me.getKey() + ": ");
System.out.println(me.getValue());
}
System.out.println();
}
}
输出
Belt: 600 Wallet: 700 Bag: 1100
代码解释
在程序中,我们首先导入 **java.util.*** 包以访问 HashMap 和其他实用程序。创建了一个名为 hm 的 HashMap 来存储键值对,例如 "Bag" 的值为 1100。**put() 方法** 用于将这些对添加到映射中。然后,我们使用 **entrySet() 方法** 检索条目,该方法返回映射条目的集合视图。迭代器用于循环遍历此集合,并在 **while 循环** 中,使用 Map.Entry 接口的 **getKey()** 和 **getValue() 方法** 打印每个条目。
这种方法有效地演示了如何在 HashMap 中存储和检索数据,同时提供了插入和迭代等基本操作的清晰示例。
广告
数据结构
网络
关系型数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP