2024年4月12日发(作者:)

HashMap是Java中常用的数据结构之一,它实现了Map接口,

允许键值对存储和访问。以下是HashMap用法举例:

```java

import p;

public class HashMapExample {

public static void main(String[] args) {

// 创建一个HashMap对象

HashMap map = new HashMap<>();

// 添加键值对

("apple", 1);

("banana", 2);

("orange", 3);

// 获取键对应的值

int appleValue = ("apple");

n("appleValue: " + appleValue); // 输出:

appleValue: 1

// 遍历键值对

for ( entry : et()) {

String key = ();

int value = ue();

n(key + " : " + value);

}

// 判断键是否存在于Map中

boolean containsApple = nsKey("apple");

n("containsApple: " + containsApple); //

输出:containsApple: true

// 删除键值对

("orange");

n("After removing orange:");

for ( entry : et()) {

String key = ();

int value = ue();

n(key + " : " + value);

}

}

}

```

在这个例子中,我们创建了一个HashMap对象,并向其中添加

了三个键值对。然后我们通过get方法获取了键"apple"对应的值,并

通过entrySet方法遍历了Map中的所有键值对。我们还使用了

containsKey方法来判断Map中是否包含键"apple",并使用remove方

法删除了键"orange"对应的键值对。