package com.newedu.jb.day19.map;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
/**
*LinkedHashMap 是HashMap的子类,具有HashMap的所有特点
* 并且因为使用了LinkedList,所以存取有序
*
* 特点:
* 1:内部依赖于哈希表和链表。
* 2:不允许键的重复。
* 3:允许null键和null值
* 4:存取有序
* 5:线程不安全,效率高
*
* 举例:
*
*LinkedHashMap<Student,String> 存储并遍历。
*
* 因为自定义类型Student做为键,所以需要对Student类型中的hashCode()和equals()进行重写。
*@author jerry
*
*/
public class LinkedHashMapDemo {
publicstatic void main(String[] args) {
//第一步:创建集合对象
LinkedHashMap<Student,String>lhm = new LinkedHashMap<>();
//第二步:创建集合元素
Stringstr1 = "001";
Studentstu1 = new Student("jerry",20);
Stringstr2 = "002";
Studentstu2 = new Student("susan",19);
Stringstr3 = "003";
Studentstu3 = new Student("peter",18);
Stringstr4 = "004";
Studentstu4 = new Student("jerry",20);
Stringstr5 = "005";
Studentstu5 = new Student("jerry",20);
//第三步:向集合中添加元素
lhm.put(stu1,str1);
lhm.put(stu2,str3);
lhm.put(stu3,str3);
lhm.put(stu4,str4);
lhm.put(stu5,str5);
//第四步:遍历集合
Set<Map.Entry<Student,String>>entries = lhm.entrySet();
for(Map.Entry<Student,String>entry : entries){
System.out.println(entry.getKey()+" -- "+ entry.getValue());
}
}
}