一、Map基本介绍
java.util.Map接口是一个存储键值对的集合,每个键对应一个值,键和值可以是任意类型,但是键不能重复。Map接口有多种实现,如HashMap、TreeMap、HashTable等。
其中HashMap是最常用的一种实现方式。HashMap底层实现是基于数组和链表的数据结构。它通过把键的hashCode()值和数组长度取余,然后把键值对保存在对应的数组下标中。如果多个键的hashCode()值取余后对应同一个下标,那么在这个下标上使用链表将键值对串起来,形成一个链表,查找时要遍历这个链表。
代码示例:
//创建一个HashMap Map<String, Integer> map = new HashMap<>(); //向map中添加键值对 map.put("apple", 1); map.put("banana", 2); //获取map中的值 int value = map.get("apple"); //遍历map中的键值对 for (Map.Entry entry : map.entrySet()) { System.out.println(entry.getKey() + " : " + entry.getValue()); }
二、Map常用操作
1、添加键值对
通过put(key, value)方法向Map中添加键值对。如果Map中已经存在该键,则会将原来的值覆盖。
代码示例:
Map<String, Integer> map = new HashMap<>(); //添加键值对 map.put("apple", 1); map.put("banana", 2);
2、获取键值对
通过get(key)方法获取Map中指定键对应的值。
代码示例:
Map<String, Integer> map = new HashMap<>(); //添加键值对 map.put("apple", 1); map.put("banana", 2); //获取键值对 int value = map.get("apple");
3、判断键是否存在
通过containsKey(key)方法判断Map中是否存在指定的键。
代码示例:
Map<String, Integer> map = new HashMap<>(); //添加键值对 map.put("apple", 1); map.put("banana", 2); //判断键是否存在 boolean containsKey = map.containsKey("apple");
4、遍历Map
通过entrySet()方法获取Map中所有的键值对,然后遍历这个集合即可。
代码示例:
Map<String, Integer> map = new HashMap<>(); //添加键值对 map.put("apple", 1); map.put("banana", 2); //遍历键值对 for (Map.Entry entry : map.entrySet()) { System.out.println(entry.getKey() + " : " + entry.getValue()); }
三、HashMap与ConcurrentHashMap的区别
HashMap是非线程安全的,如果多个线程同时访问一个HashMap实例,可能会导致数据不一致的问题。而ConcurrentHashMap则是线程安全的,它采用了分段锁的机制,将整个Map分成多个小的区域,每个区域有自己的锁,这样多个线程在访问不同的区域时不会相互影响,从而保证线程安全。
代码示例:
//创建一个HashMap Map<String, Integer> hashMap = new HashMap<>(); //创建一个ConcurrentHashMap Map<String, Integer> concurrentHashMap = new ConcurrentHashMap<>();
四、Map遍历性能比较
在遍历Map时,常见的遍历方式有通过entrySet()方法遍历和通过keySet()方法遍历。但是这两种方式的性能存在一定的差异。
entrySet()方式在遍历Map时,每次获取键值对时需要同时获取键和值,会产生一定的性能损耗。而keySet()方式只获取键,效率更高。
代码示例:
Map<String, Integer> map = new HashMap<>(); //添加键值对 map.put("apple", 1); map.put("banana", 2); //通过entrySet()方式遍历Map long start1 = System.currentTimeMillis(); for (Map.Entry entry : map.entrySet()) { System.out.println(entry.getKey() + " : " + entry.getValue()); } long end1 = System.currentTimeMillis(); //通过keySet()方式遍历Map long start2 = System.currentTimeMillis(); for (String key : map.keySet()) { Integer value = map.get(key); System.out.println(key + " : " + value); } long end2 = System.currentTimeMillis(); System.out.println("entrySet()方式遍历Map耗时:" + (end1 - start1) + "ms"); System.out.println("keySet()方式遍历Map耗时:" + (end2 - start2) + "ms");