Java Hashmap
1. 介绍¶
有点复杂,待整理。
2. 常用方法¶
首先,我们应该知道HashMap类实现了Map接口,所以实现了Map常用的一些方法。
序号 | 方法名 | 作用 |
---|---|---|
1 | public V put(K key, V value) |
插入键值对数据 |
2 | public V get(Object key) |
根据键值获取键值对值数据 |
3 | public int size() |
获取Map中键值对的个数 |
4 | public boolean containsKey(Object key) |
判断Map集合中是否包含键为key的键值对 |
5 | boolean containsValue(Object value) |
判断Map集合中是否包含值为value的键值对 |
6 | public boolean isEmpty() |
判断Map集合中是否没有任何键值对 |
7 | public void clear() |
清空Map集合中所有的键值对 |
8 | public V remove(Object key) |
根据键值删除Map中键值对 |
code
package MapDemo; import java.util.*; /** * @author summer * @create 2020-02-07 10:49 * map存储的是k-v键值对映射的数据 * 实现子类: * HashMap:数据+链表(1.7) 数组+链表+红黑树(1.8) * LinkedHashMap:链表 * TreeMap:红黑树 * * 基本api操作: * 增加: * put(k,v) 添加元素 * 查找: * isEmpty 判断是否为空 * size 返回map的大小 * containsKey * containsValue * get * 删除: * clear 清空集合中的所有元素 * remove:删除指定元素 * Map.entry:表示的是K-V组合的一组映射关系,key和value成组出现 * * hashmap跟hashtable的区别: * 1、hashmap线程不安全,效率比较高,hashtable线程安全,效率低 * 2、hashmap中key和value都可以为空,hashtable不允许为空 * * * hashmap初始值为2的N次幂, * 1、方便进行&操作,提高效率,&要比取模运算效率要高 * hash & (initCapacity-1) * 2、在扩容之后涉及到元素的迁移过程,迁移的时候只需要判断二进制的前一位是0或者是1即可 * 如果是0,表示新数组和就数组的下标位置不变,如果是1,只需要将索引位置加上旧的数组的长度值即为新数组的下标 * 1.7源码知识点: 数组+链表 * 1、默认初始容量 * 2、加载因子 * 3、put操作 * 1、设置值,计算hash * 2、扩容操作 * 3、数据迁移的过程 * 1.8源码知识点: 数组+链表+红黑树 */ public class mapdemo1 { public static void main(String[] args) { HashMap<String,Integer> hm = new HashMap<>(); hm.put("k1",123); hm.put("k2",456); hm.put("k3",456); System.out.println("hm是否为空: "+hm.isEmpty()); System.out.println("hm长度是: "+hm.size()); System.out.println("hm是否包含键 k1: "+hm.containsKey("k1")); System.out.println("hm是否包含值123: "+hm.containsValue(123)); System.out.println("获取hm键是k1对应的值"+hm.get("k1")); System.out.println("hm删除键k1之前: "+hm); hm.remove("k1"); System.out.println("hm删除键k1后: "+hm); Set<String> keys = hm.keySet(); for (String key:keys) { System.out.println(key+"="+hm.get(key)); } System.out.println("-----增强for-----"); // Collection<Integer> values = hm.values(); // 只能获取values值,不能根据value获取key的值 for (Integer i:hm.values()) { System.out.println(i); } //迭代器 System.out.println("-----迭代器-----"); Set<String> keys2 = hm.keySet(); Iterator<String> IteratorData = keys2.iterator(); while (IteratorData.hasNext()){ String key = IteratorData.next(); System.out.println(hm.get(key)); } System.out.println("-----map.entry-----"); Set<Map.Entry<String, Integer>> entries = hm.entrySet(); Iterator<Map.Entry<String, Integer>> iterator = entries.iterator(); while (iterator.hasNext()){ Map.Entry<String, Integer> next = iterator.next(); System.out.println(next.getKey()+"="+next.getValue()); } System.out.println("hm清空之前: "+hm); hm.clear(); System.out.println("hm清空之后: "+hm); } }
输出
hm是否为空: false hm长度是: 3 hm是否包含键 k1: true hm是否包含值123: true 获取hm键是k1对应的值123 hm删除键k1之前: {k1=123, k2=456, k3=456} hm删除键k1后: {k2=456, k3=456} k2=456 k3=456 -----增强for----- 456 456 -----迭代器----- 456 456 -----map.entry----- k2=456 k3=456 hm清空之前: {k2=456, k3=456} hm清空之后: {}