一、HashMap的简单介绍
HashMap是非常常见的一种数据结构,这种数据结构可以存储键值对(Key-Value)。
HashMap的主干是一个Entry数组,Entry是HashMap的基本组成单元,每个Entry包含一个键值对,所以HashMap可以看作是保存了两个对象之间映射关系的一种集合。
//HashMap的主干数组,可以看到就是一个Entry数组,初始值为空数组{}。
transient Entry<K,V>[] table = (Entry<K,V>[]) EMPTY_TABLE;
二、HashMap常用方法
1.put(),添加一个键值对
添加到map的数据与list不一样,是没有顺序的,其顺序根据哈希算法得出。
public static void main(String[] args) {
HashMap<String, Integer> map = new HashMap<>();
map.put("aaa", 0);
map.put("bbb", 1);
System.out.println(map);
}
2.putAll()
可以把一个HashMap集合对象,整体加入到另外一个HashMap对象中。
public static void main(String[] args) {
HashMap<String, Integer> map1 = new HashMap<>();
map1.put("aaa", 0);
map1.put("bbb", 1);
HashMap<String, Integer> map2 = new HashMap<>();
map2.putAll(map1);
System.out.println(map2);
}
3.remove(),删除一个键值对
remove方法内是针对Key进行删除的。
public static void main(String[] args) {
HashMap<String, Integer> map = new HashMap<>();
map.put("aaa", 0);
map.put("bbb", 1);
System.out.println(map);
map.remove("aaa");
System.out.println(map);
}
4.get(),查询value
传入key,就可以查询到value。
public static void main(String[] args) {