HashMap的简单使用
- JDK1.2版本,线程不安全,运行效率快;允许用null作为key或是value。
- 存储结构:哈希表(数组+链表+红黑树)
- 使用key的 HashCode() equals()作为重复判断依据
1.添加元素
HashMap<Teacher,String> hm=new HashMap<>();
Teacher t1=new Teacher("孙悟空",24);
Teacher t2=new Teacher("猪八戒",36);
Teacher t3=new Teacher("沙悟净",28);
hm.put(t1,"水帘洞");
hm.put(t2,"高老庄");
hm.put(t3,"流沙河");
hm.put(new Teacher("猪八戒",36),"净坛");//替换t2对象
//重写equals方法和hashcode方法,判断当姓名和年龄相同时视为同一个对象,无法添加,只能替换value
System.out.println("集合元素个数为:"+hm.size());
System.out.println(hm.toString());
2.删除元素
hm.remove(t1);
System.out.println("集合元素个数为:"+hm.size());
System.out.println(hm.toString());
3.遍历元素
//1.使用keySet()
for (Teacher teacher : hm.keySet()) {
System.out.println(teacher+"=="+hm.get(teacher));
}
System.out.println("----------------");
//2.使用entrySet()
for (Map.Entry<Teacher, String> entry : hm.entrySet()) {
System.out.println(entry);
}
System.out.println("----------------");
4.判断
//判断
System.out.println(hm.containsKey(new Teacher("猪八戒",36)));
//需重写equals方法和hashcode方法
System.out.println(hm.containsValue("水帘洞"));
System.out.println(hm.isEmpty());
5.总结
-
HashMap刚创建时,table是null, 为了节省空间,当添加第一 个元素是,table容量调整为16。
-
当元素个数大于闽值(16*0.75=12)时上会进行扩容,扩容后大小为原来的2倍。目的是减少调整元素的个数。
-
jdk1.8当每个链表长度大于8,并且元素个数大于等于64时,会调整为红黑树,目的提高执行效率。
-
jdk1.8当链表长度小于6时,调整成链表。
-
jdk1.8以前,链表时头插入,jdk1 .8以后时是尾插入。
TreeMap的简单使用
●实现了SortedMap接口(是Map的子接口),可以对key自动排序。
●存储结构:红黑树
创建集合与实现接口方法重写
//创建集合(定制比较)
TreeMap<Teacher,String> teacher=new TreeMap<>(new Comparator<Teacher>() {
//根据要求重写比较方法
@Override
public int compare(Teacher o1, Teacher o2) {
return 0;
}
});
其余添加元素,删除元素,遍历等方法与HashMap类似。。不再赘述。。