JAVA全系列 教程
3762个小节阅读:7093.6k
目录
C语言快速入门
JAVA全系列 教程
面向对象的程序设计语言
Python全系列 教程
Python3.x版本,未来主流的版本
人工智能 教程
顺势而为,AI创新未来
大厂算法 教程
算法,程序员自我提升必经之路
C++ 教程
一门通用计算机编程语言
微服务 教程
目前业界流行的框架组合
web前端全系列 教程
通向WEB技术世界的钥匙
大数据全系列 教程
站在云端操控万千数据
AIGC全能工具班
A A
White Night
HashMap采用哈希算法实现,是Map接口最常用的实现类。 由于底层采用了哈希表存储数据,我们要求键不能重复,如果发生重复,新的键值对会替换旧的键值对。 HashMap在查找、删除、修改方面都有非常高的效率。
xxxxxxxxxx
public class HashMapTest {
public static void main(String[] args) {
//实例化HashMap容器
Map<String,String> map = new HashMap<>();
//添加元素
map.put("a","A");
map.put("b","B");
map.put("c","C");
map.put("a","D");
//获取容器中元素数量
int size = map.size();
System.out.println(size);
System.out.println("---------------");
//获取元素
//方式一
String v = map.get("a");
System.out.println(v);
System.out.println("---------------");
//方式二
Set<String> keys = map.keySet();
for(String key:keys){
String v1 = map.get(key);
System.out.println(key+" ---- "+v1);
}
System.out.println("-------------------");
//方式三
Set<Map.Entry<String,String>> entrySet = map.entrySet();
for(Map.Entry<String,String> entry:entrySet){
String key = entry.getKey();
String v2 = entry.getValue();
System.out.println(key+" ---------- "+v2);
}
System.out.println("--------------------");
//Map容器的并集操作
Map<String,String> map2 = new HashMap<>();
map2.put("f","F");
map2.put("c","CC");
map.putAll(map2);
Set<String> keys2 = map.keySet();
for(String key:keys2){
System.out.println("key: "+key+" Value: "+map.get(key));
}
System.out.println("---------------");
//删除元素
String v3 = map.remove("a");
System.out.println(v3);
Set<String> keys3 = map.keySet();
for(String key:keys3){
System.out.println("key: "+key+" Value: "+map.get(key));
}
System.out.println("-------------------");
//判断Key是否存在
boolean b = map.containsKey("b");
System.out.println(b);
//判断Value是否存在
boolean cc = map.containsValue("CC");
System.out.println(cc);
}
}
HashTable类和HashMap用法几乎一样,底层实现几乎一样,只不过HashTable的方法添加了synchronized关键字确保线程同步检查,效率较低。
HashMap与HashTable的区别
- HashMap: 线程不安全,效率高。允许key或value为null
- HashTable: 线程安全,效率低。不允许key或value为null