Java中的HashMap详解【updating】
1.类简介
HashMap就是一个散列表,它是通过**“拉链法”**解决哈希冲突的。
一般来说,哈希冲突有三种解决办法:
- 1.拉链法[用链表存储起来冲突的数据]
- 2.开放定址法[继续往后寻找第一个空位]
- 3.二次探测法[再次使用一次hash函数进行选位]
HashMap继承AbstractMap这个抽象类,实现Map这个接口。
HashMap的底层实现是数组+链表。意思就是:HashMap中存储的每一个对象都是Node型的节点,这个节点包含key,value,以及指向下一个Node节点的next。当从元素的key映射取位置的时候,会将节点的key的hashcode执行哈希函数,取到数组中的位置。如果这个位置上已经有了元素,则采用头插法的原则在这个节点上插入本节点。这个过程有些类似于图的邻接表存储,他们的实现原理都是相似的,但是作用的结果不同。
2.方法简介
2.1 put()方法
- 方法释义
/**
Associates the specified value with the specified key in this map. If the map previously contained a mapping for the key, the old value is replaced.
在这个map中,将指定值与指定键关联起来。如果map之前就包含一个键映射,那么旧值将会被替换。
@param key key with which the specified value is to be associated
@param value value to be associated with the specified key
@return the previous value associated with key, or null if there was no mapping for key.
(A null return can also indicate that the map previously associated null with key.)
与这个key相关联的之前值 ,如果map中没有这个key,则是null。
(如果返回值是null,也可能表示之前的map中与key = null 相对应的值)
*/
- 方法代码
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
2.2 简单测试
package Test;
import java.text.SimpleDateFormat;
import java.util.*;
public class JavaTest {
public static void main(String[] args) {
test4();
}
public static void test4(){
HashMap<Integer, String> map = new HashMap<Integer, String>();
String res = map.put(1, "hadoop");
System.out.println(res); // null
res = map.put(1, "spark");
System.out.println(res);// hadoop
System.out.println(map.get(1));// spark
res = map.put(null, "wahaha"); //null ; key = null ,but value is not null
System.out.println(res);
}
}
2.3 输出结果
null
hadoop
spark
null
简单说一下结果输出:
第一:是因为,初始情况下,map中没有key=1的键,所以put之后的返回值是null;
第二:hadoop,因为只有有过插入key=1的键,所以导致这次的返回值就是之前key=1的值
第三:spark,说明这次的插入值覆盖了上次的键值对
第四:如果插入key=null的值,那么返回值也是null
3. Map的遍历输出
public static void test8(){
Map<String, String> map = new HashMap<String,String>();
map.put("normal","hadoop");
map.put("nice", "spark");
Set set = map.keySet();//获取map的keySet
Iterator it = set.iterator();//使用Iterator拿到keySet的首地址
/*while(it.hasNext()){
String value = map.get(it);
System.out.println("key = "+it+", value = "+value);
}
=>上面这个代码会造成死循环
*/
while(it.hasNext()){//依次遍历输出
String s = (String)it.next();
String value = map.get(s);
System.out.println("key = "+s+", value = "+value.toString());
}
}
输出结果如下:
key = normal, value = hadoop
key = nice, value = spark
4.Map中的不会出现重复的key值
验证如下:
public static void test15(){
HashMap<String, Integer> map = new HashMap<String,Integer>();
map.put("27.208.85.8", 8060);
map.put("27.208.85.8",1202);
Set entry = map.keySet();
Iterator it = entry.iterator();
while(it.hasNext()){//依次遍历输出
String s = (String)it.next();
Integer value = map.get(s);
System.out.println("key = "+s+", value = "+value);
}
}
执行的结果如下:
key = 27.208.85.8, value = 1202
可以知道HashMap中是不可能存在重复的key值【因为HashMap
的实现原理是哈希表】
【存在疑问】