首页  >  文章  >  Java  >  Java 中的 HashMap

Java 中的 HashMap

王林
王林原创
2024-08-30 15:34:13238浏览

在Java中,你可以使用数组来存储数据,但是每当需要以键和值的方式存储或检索数据时,你就必须使用HashMap。 Hashmap 是 Java 中的一个集合,属于称为 Map 的接口层次结构。在这篇文章中,我们将从Java编程的角度讨论Hashmap。

语法:

广告 该类别中的热门课程 JAVA 掌握 - 专业化 | 78 课程系列 | 15 次模拟测试

要在代码中使用HashMap,必须导入(导入java.util.HashMap包)或其父类。

import java.util.HashMap;
import java.util.Map;
HashMap<datatypeOfkey, dataytpeOfValue> <name_of_hashMap> =new HashMap<datatypeOfkey, dataytpeOfValue> ();

其中 datatypeOfkey 和 dataytpeOfValue 可以是 Integer 或 String。

示例:

Map<String, String> newHashMap = new HashMap<>();

HashMap 在 Java 中如何工作?

Hashmap 使用哈希技术来存储和检索元素。对于存储,它使用称为存储桶的链表。它在键上使用两个方法:equals() 和 hashCode() 来进行插入和检索操作。插入时,hashCode决定存储的桶。之后,hashCode 再次检查是否已经存在具有相同 hashCode 的 key;如果是,则将该值替换为新值。如果没有,则创建新的映射,并将值存储在其中。在检索数据时,hashCode决定了要查找的桶。之后,hashCode() 和 equals() 获取值并返回该值。如果不存在任何值,则返回 null。

Java 中的 HashMap 构造函数

它有四个构造函数,如下所述。

  1. HashMap():默认的,负载因子为0.75,容量为16。
  2. HashMap(int ): 使用其参数中定义的容量创建 HashMap。这里的负载因子是默认的。
  3. HashMap(int , float ): 使用其参数中定义的容量和负载因子创建 HashMap。
  4. HashMap(Map m): 按照参数映射中的定义创建 HashMap。

Java 中 HashMap 的 13 个方法

这里讨论的以下所有方法都可以使用,无论任何版本的 Java。

  1. public value get(Object key): 用于获取对应键的值。
  2. public value put(K key, V value): 插入相应键的参数中提到的值。
  3. public boolean containsKey(Object key):决定key是否存在,注意返回类型为Boolean。
  4. public boolean containsValue(Object value):决定值是否存在,注意返回类型是Boolean。
  5. public V remove(Object key): 清除代码中指定的特定键及其值形式的 HashMap。
  6. public void clear(): 如上所述清除 HashMap 中的所有键和值。
  7. public boolean isEmpty(): 验证 HashMap 是否为空。
  8. 对象克隆():此方法返回 HashMap 的映射,用于克隆到另一个 HashMap。
  9. public int size(): 返回 HashMap 中存在的大小,表示有多少个键值对。
  10. 公共集>> EntrySet():该方法返回HashMap中映射的集合。
  11. 公共集 keySet():该方法返回HashMap中的key集合。
  12. public void putAll(Map ): 将整个地图内容复制到另一个。
  13. 集合values():你可以获得HashMap所有值的集合。

Java 中 HashMap 的示例

HashMap 是一个基于 Map 的集合类,用于存储键值对。让我们看几个例子。

示例#1

我们将在这里讨论 HashMap 的一些代码示例。您应该通过自己编写代码来练习代码,并在 java 编译器上运行以检查输出。您可以将输出与给定的输出进行匹配以进行验证。创建 HashMap 并在其中插入数据。

代码:

import java.util.HashMap;
import java.util.Map;
public class CreateHashMapExample {
public static void main(String[] args) {
// Creating a HashMap
Map<String, String> newHashMap = new HashMap<>();
// Addition of key and value
newHashMap.put("Key1", "Java");
newHashMap.put("Key2", "C++");
newHashMap.put("Key3", "Python");
// Addition of new key and value
newHashMap.putIfAbsent("Key4", "Ruby");
System.out.println(newHashMap);
}
}

输出:

Java 中的 HashMap

示例#2

让我们再举一个例子,我们将字符串作为键,将整数作为值。这里我们将测量键及其对应的值(以英寸为单位)。

代码:

import java.util.HashMap;
public class CreateHashMapExample2 {
public static void main(String[] args) {
// Create a HashMap object called measurement
HashMap<String, Integer> ms = new HashMap<String, Integer>();
// Add keys and values (Name and phone number of the person)
ms.put("S", 35);
ms.put("M", 38);
ms.put("L", 40);
ms.put("XL", 42);
for (String key : ms.keySet()) {
System.out.println("measurement of " + key + " in inch is: " + ms.get(key));
}
}
}

输出:

Java 中的 HashMap

Example #3

Here we will do multiple things. We will first create a Hashmap; we will then get its values one by one. After that, we will copy all data of the HashMap to a brand new HashMap. After that, we will remove one item and gets their sizes. If the size is lower by one, the decrease of size by removal is confirmed.

Code:

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
public class HashMapInJava {
public static void main(String[] args) {
Map<String, String> newHashMap = new HashMap<>();
// Addition of key and value
newHashMap.put("Key1", "Lenovo");
newHashMap.put("Key2", "Motorola");
newHashMap.put("Key3", "Nokia");
newHashMap.put("Key4", null);
newHashMap.put(null, "Sony");
System.out.println("Original map contains:" + newHashMap);
//getting size of Hashmap
System.out.println("Size of original Map is:" + newHashMap.size());
//copy contains of one Hashmap to another
Map copyHashMap = new HashMap<>();
copyHashMap.putAll(newHashMap);
System.out.println("copyHashMap mappings= " + copyHashMap);
//Removal of null key
String nullKeyValue = copyHashMap.remove(null);
System.out.println("copyHashMap null key value = " + nullKeyValue);
System.out.println("copyHashMap after removing null key = " + copyHashMap);
System.out.println("Size of copyHashMap is:" + copyHashMap.size());
}
}

Output:

Java 中的 HashMap

Did you notice one thing in the output of HashMap in all of our examples while we print the key and values? The print is not in sorted order. Hashmap is not like an array, so scan and print need to be sorted; it can pick random based on its hash value.

Conclusion

You should use HashMap when your code or use case requires the handling of data in key-value pairs. In this article, we have learned about hashmaps in Java with code examples. First, however, you should practice writing codes on your own to master this topic.

Recommended Article

This is a guide to the HashMap in Java. Here we discuss Introduction to HashMap in Java and its Methods along with Code implementation and Output. You can also go through our suggested articles to learn more –

  1. HTML Frames
  2. HTML Attributes
  3. What is JVM?
  4. Java ClassNotFoundException

以上是Java 中的 HashMap的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn