Map集合的实现类,HashMap
HashMap
存储结构:哈希表(数组+链表+红黑树)
线程不安全,运行效率快,允许使用null,key,value
默认初始容量16,默认加载因子 0.75(使用容量超过总容量75%时,扩容)
hashmap
创建集合:
HashMap<Student,String> hashMap = new HashMap<Student, String>();
key为Student类,value为String类
判断重复
存入元素时去除重复,重写hashcode和equals
Student s1 = new Student("张三",1001);
Student s2 = new Student("李四",1002);
Student s3 = new Student("王五",1003);
hashMap.put(s1,"北京");
hashMap.put(s2,"上海");
hashMap.put(s3,"广州");
//重写Student类中的hashcode和equals方法,判断重复
hashMap.put(new Student("张三",1001),"北京");
hashMap.contains(new Student("张三",1001),"北京")
遍历:
foreach遍历:
//遍历1.keyset
for (Student key:hashMap.keySet()
) {
System.out.println(key+"--"+hashMap.get(key));
}
System.out.println("------------");
//遍历2.entryset
for (HashMap.Entry<Student,String> kv:hashMap.entrySet()
) {
System.out.println(kv.getKey()+"--"+kv.getValue());
}
迭代器遍历:
temp = iterator.next()需要赋一个临时值,直接把iterator.next()当作key使用会报错赋值时需要注意temp的类型,keyset中,迭代的是key值,所以temp的类型是Student。
entryset中,迭代的是封装好的key:value值(Entry),所以temp的类型是
HashMap.Entry<Student,String>
//Set<Student> key = hashMap.keySet();
Iterator<Student>it =hashMap.keySet().iterator();
while (it.hasNext()){
Student keytemp =it.next();
System.out.println(keytemp+"--"+hashMap.get(keytemp));
}
//entryset的迭代
Iterator<HashMap.Entry<Student,String>>iterator = hashMap.entrySet().iterator();
while (iterator.hasNext()){
HashMap.Entry tempentry = iterator.next();
System.out.println(tempentry.getKey()+"--"+tempentry.getValue());
}
HashMap源码分析 ?
- HashMap刚创建时,table是null,为了节省空间,当添加第一个元素时,table容量调整为16.
- 当元素个数大于阈值(16*0.75)时,会进行扩容,扩容后大小为原来的两倍。目的是为了减少调整元素的个数。
- jdk1.8当每个链表长度大于8,并且元素个数大于等于64时,会调整为红黑树,目的时提高执行效率
- 当链表长度小于6时,调整为链表
- jdk1.8以前,链表是头插入,以后是尾插入
HashSet和HashMap
HashSet的底层其实就是HashMap,用的是HashMap的key部分
HashTable
线程安全,运行效率慢,不允许null作为key或value
子类 Properties
HashTable的子类,要求key和value都是String,通常用于配置文件的读取。
保存在流中,或者从流中加载
TreeMap
实现了 SortedMap接口(Map的子接口),可以对key自动排序
底层为红黑树。左边节点小于右边节点
与TreeSet相同,要制定比较规则,即实现Comparable接口
public class Person implements Comparable<Person>
并重写compareTo方法
@Override
public int compareTo(Person o) {
int n1 = this.getName().compareTo(o.getName());
int n2 = this.getStudentnum()-o.getStudentnum();
return n1==0?n2:n1;
}