**
* HashMap的使用
* 存储结构:哈希表(数组+列表+红黑树)
*使用key的hashcode和equals作为重复
*/
public class Aplication {
public static void main(String[] args) {
//创建集合
HashMap<Student,String> map = new HashMap<>();
//添加元素
Student s1 = new Student("孙悟空",101);
Student s2 = new Student("猪八戒",102);
Student s3 = new Student("沙和尚",103);
map.put(s1,"北京");
map.put(s2,"上海");
map.put(s3,"杭州");
//删除元素
// map.remove(new Student("孙悟空",101));
// System.out.println(map.size());
//遍历元素
//1.keySet方法
for (Student s:map.keySet()){
System.out.println(s.toString()+"===="+map.get(s));
}
//2.entrySet方法
for (Map.Entry<Student,String> entry:map.entrySet()){
System.out.println(entry.getKey()+"==="+entry.getValue());
}
//判断
System.out.println(map.containsKey(s1));
System.out.println(map.containsValue("杭州"));
}
}
HashMap源代码分析:
- HashMap刚创建时,table是null,为了节省空间,当添加第一个元素,table容量调整为16.
- 当元素个数大于阈值(16*0.75=12)时,会进行扩容,扩容后大小为原来的2倍。目的是减少调整元素的个数。
- jdk1.8 当每个链表长度大于8,并且元素个数大于等于64时,会调整为红黑树,目的是提高执行效率。
- jdk1.8 当链表长度小于6时,调整为链表
- jdk1.8以前,链表头插入,jdk1.8以后是尾插入