hashmap Java用法
时间: 2024-09-13 10:01:38 浏览: 55
HashMap是Java中的一个非常重要的集合类,它实现了Map接口,用于存储键值对。HashMap允许null作为键和值。HashMap基于散列原理,它根据键的hashCode值存储数据,大多数情况下,存储和访问数据的速度非常快。
HashMap的基本用法如下:
1. 创建HashMap对象:
```java
Map<K,V> map = new HashMap<K,V>();
```
其中,`K` 表示键的类型,`V` 表示值的类型。
2. 插入键值对:
```java
map.put(key, value);
```
键值对会被存储在HashMap中。如果键是唯一的,那么这个键值对会被添加到Map中;如果键已经存在,则会更新对应的值。
3. 获取值:
```java
V value = map.get(key);
```
根据键获取值,如果Map中包含该键的映射关系,则返回对应的值,否则返回null。
4. 检查是否包含某个键:
```java
boolean containsKey = map.containsKey(key);
```
5. 检查是否包含某个值:
```java
boolean containsValue = map.containsValue(value);
```
6. 删除键值对:
```java
map.remove(key);
```
7. 获取HashMap的大小(键值对的数量):
```java
int size = map.size();
```
8. 清空HashMap:
```java
map.clear();
```
阅读全文
相关推荐

















