在Java中,哈希表通常指HashMap
(非线程安全)或Hashtable
(线程安全),两者均实现Map
接口。常用操作如下:
1. 包引入与哈希表创建
```java
import java.util.HashMap; // 非线程安全
import java.util.Hashtable; // 线程安全
// 创建HashMap(推荐)
Map<String, Integer> map = new HashMap<>();
// 创建Hashtable(线程安全场景)
Map<String, Integer> table = new Hashtable<>();
2. 键值对添加
map.put("apple", 1);
map.put("banana", 2);
map.put("cherry", 3);
3. 元素访问
// 通过键获取值
int value = map.get("apple"); // 返回1
// 检查键存在
boolean hasKey = map.containsKey("banana"); // true
// 检查值存在
boolean hasValue = map.containsValue(3); // true
4. 元素删除
// 按键删除
map.remove("cherry");
// 清空哈希表
map.clear();
5. 哈希表遍历
// 遍历键值对
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
// 遍历键集合
for (String key : map.keySet()) {
System.out.println(key);
}
// 遍历值集合
for (int val : map.values()) {
System.out.println(val);
}
// Lambda表达式遍历(Java 8+)
map.forEach((k, v) -> System.out.println(k + ": " + v));
6. 其他实用方法
// 获取元素数量
int size = map.size();
// 判空检测
boolean isEmpty = map.isEmpty();
// 合并哈希表(Java 8+)
Map<String, Integer> otherMap = new HashMap<>();
otherMap.put("date", 4);
map.putAll(otherMap);
注意事项
- 键唯一性:重复键会覆盖旧值
- 空值限制:
HashMap
允许null键值,Hashtable
禁止 - 线程安全:多线程环境推荐
ConcurrentHashMap
完整示例
import java.util.HashMap;
import java.util.Map;
public class HashMapDemo {
public static void main(String[] args) {
Map<String, Integer> fruits = new HashMap<>();
// 添加元素
fruits.put("apple", 1);
fruits.put("banana", 2);
fruits.put("cherry", 3);
// 元素获取
System.out.println("Apple数量: " + fruits.get("apple"));
// 遍历输出
System.out.println("当前水果清单:");
fruits.forEach((k, v) -> System.out.println(k + ": " + v));
// 元素删除
fruits.remove("banana");
System.out.println("删除后大小: " + fruits.size());
}
}
该示例完整演示了哈希表的创建、增删改查和遍历操作。
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END
暂无评论内容