//赋值
hashMap.put(“id”,1);
hashMap.put(“name”,“张三”);
//取值
// Integer id = (Integer) hashMap.get(“id”);
// String name = (String) hashMap.get(“name”);
//获取所有的key值
Set keys=hashMap.keySet();//将map的key转换成set集合
Iterator keyInterator1=keys.iterator();//将keys转换成迭代器
System.out.println(“map的所有key值===============”);
while (keyInterator1.hasNext()){
System.out.println(keyInterator1.next() );
}
System.out.println(“map的所有value值===============”);
Collection values=hashMap.values();
Iterator keyInterator2=values.iterator();
while (keyInterator2.hasNext()){
System.out.println(keyInterator2.next());
}
请看结果:
是不是与上面的赋值对应上了
下面来介绍一下HashMap的性能以及安全问题
刚刚说了HashMap的存储是基于hash算法实现的,那他具体是如何实现的呢?当程序执行HashMap的put方法时,将调用String的 hashCode() 方法得到其 hashCode 值,在这里说明一下HashCode的因子是31,最后会根据计算出来的HashCode存放Map的元素.
扩容机制
我们先来看一下HashMap的初始化,HashMap提供了4中构造函数:
//无参构造
Map<String,Object> map1 = new HashMap<String, Object>();
//有参构造 传入初始容器大小
Map<String,Object> map2 = new HashMap<String, Object>(100);
//有参构造 传入初始容器以及负载因子
Map<String,Object> map3 = new HashMap<String, Object>(100,0.8f);
//有参构造 讲一个map赋值给一个新的map
Map<String,Object> map4 = new HashMap<String, Object>(map1);
我们现在分别来看一下这几个构造函数的源码:
1.new HashMap()
/**
-
Constructs an empty HashMap with the default initial capacity
-
(16) and the default load factor (0.75).
*/
public HashMap() {
this.loadFactor =