java零基础Ⅱ-- 5.集合
一、集合的理解和好处
前我们保存多个数据使用的是数组,那么数组有不足的地方,我们分析一下
数组
1)长度开始时必须指定,而且一旦指定,不能更改
2)保存的必须为同一个类型的元素
3)使用数组进行增加/删除元素的示意代码 - 比较麻烦
//写出Person数组扩容示意代码
Person[] pers = new Person[1];//大小是1
pers[0] = new Person();
//增加新的Person对象?
Person[] pers2 = new Person[pers.length + 1];//新创建一个数组
for(){...} //拷贝pers数组的元素到pers2
pers2[pers2.length-1] = new Person();//添加新的对象
集合
1)可以动态保存任意对个对象,使用比较方便
2)提供了一系列方便的操作对象的方法:add、remove、set、ge
t等
3)使用集合添加元素,删除新元素的示意代码 - 简洁了
二、集合框架体系图
Java的集合类很多,主要分为两大类
- Collection
- Map
Collection
体系图:
Map
体系图:
1、集合主要是两组(单例集合、双列集合)
2、Collection
接口有两个重要的子接口 List、Set
,它们的实现子类都是单例集合
3、Map
接口的实现子类 是双列集合,存放的是 K-V
三、Collection
Collection接口实现类的特点
package java.util;
public interface Collection<E> extends Iterable<E> {..}
1、Collection 实现子接口可以存放多个元素,每个元素可以是Object
2、有些 Collection 的实现类,可以存放重复的元素,有些不可以
3、有些 Collection 的实现类,有些是有序的(List),有些不是有序(Set)
4、Collection 接口没有直接的实现子类,是通过它的子类接口 Set 和 List 来实现的
Collection 接口常用方法
add
:添加单个元素remove
:删除指定的元素contains
:查找元素是否存在size
:获取元素个数isEmpty
:判断是否为空clear
:清空addAll
:添加多个元素containsAll
:查找多个元素是否都存在removeAll
:删除多个元素
Collection 接口常用方法,以实现子类 ArrayList 来演示。
package com.zzpedu.collection_;
import java.util.ArrayList;
import java.util.List;
public class CollectionMethod {
@SuppressWarnings({"all"})
public static void main(String[] args) {
List list = new ArrayList();
//add:添加单个元素
list.add("jack");
list.add(10); // list.add(new Integer(10));
list.add(true);
System.out.println("list=" + list);//[jack, 10, true]
//remove:删除指定的元素
//list.remove(0);//删除第一个元素
list.remove(true);//指定删除某个元素
System.out.println("list=" + list);//[jack, 10]
//contains:查找元素是否存在
System.out.println(list.contains("jack"));//true
//size:获取元素个数
System.out.println(list.size());//2
// isEmpty:判断是否为空
System.out.println(list.isEmpty());//false
//clear:清空
list.clear();
System.out.println("list=" + list);//[]
//addAll:添加多个元素
List list2 = new ArrayList();
list2.add("西游记");
list2.add("水浒传");
list.addAll(list2);
System.out.println("list=" + list);//[西游记, 水浒传]
//containsAll:查找多个元素是否都存在
System.out.println(list.containsAll(list2));//true
//removeAll:删除多个元素
list.add("红楼梦");
System.out.println(list.removeAll(list2));//true
System.out.println("list=" + list);//[红楼梦]
}
}
===========控制台输出============
list=[jack, 10, true]
list=[jack, 10]
true
2
false
list=[]
list=[西游记, 水浒传]
true
true
list=[红楼梦]
Collection 接口遍历元素方式1 -使用Iterator(迭代器)
基本介绍
package java.lang;
public interface Iterable<T> {
/**
* Returns an iterator over elements of type {@code T}.
*
* @return an Iterator.
*/
@NotNull
Iterator<T> iterator();
....
}
1)Iterator对象称为迭代器,主要用于遍历 Collection 集合中元素。
2)所有实现了 Collection 接口的集合类都有一个 iterator() 方法, 用以返回一个实现了 Iterator 接口对象,即返回一个迭代器。
3)Iterator 仅用于遍历集合,Iterator 本身并不存方法对象。
迭代器的执行过程
Iterator iterator = coll.iterator(); //得到一个集合的迭代器
//hasNext(); //判断是否还有下一个元素
while(iterator.hasNext()){
//next(); //作用:1、指针下移 2、将下移以后集合位置上的元素返回
System.out.println(iterator.next());
}
package java.util;
public interface Iterator<E> {
/**
* Returns {@code true} if the iteration has more elements.
* (In other words, returns {@code true} if {@link #next} would
* return an element rather than throwing an exception.)
*
* @return {@code true} if the iteration has more elements
*/
@Contract(pure = true)
boolean hasNext();
...
}
Iterator接口方法
注意:在调用iterator.next()
方法之前必须要调用iterator.hasNext()
进行检测。若不调用,且下一条记录无效,直接调用iterator.next()
会抛出 NoSuchElementException
异常。
public class CollectionIterator {
@SuppressWarnings({"all"})
public static void main(String[] args) {
Collection collection = new ArrayList();
collection.add(new Book("西游记","吴承恩",99.0));
collection.add(new Book("小李飞刀","古龙",98.8));
collection.add(new Book("红楼梦","曹雪芹",90.5));
//System.out.println("collection=" + collection);
//遍历集合
//1、先得到 collection 的迭代器
Iterator iterator = collection.iterator();
//2、使用while循环遍历
while (iterator.hasNext()){//判断是否还有数据
//返回下一个元素,类型是Object
Object obj = iterator.next();
System.out.println("obj=" + obj);
}
//显示所有的快捷键的的快捷键 ctrl + j
//3、当退出while循环后,这时iterator迭代器,指向最后的元素
// iterator.next();//抛出 NoSuchElementException 异常
//4、如果希望再次遍历,需要重置我们的迭代器
iterator = collection.iterator();
System.out.println("---------第二次遍历---------");
while (iterator.hasNext()){//判断是否还有数据
//返回下一个元素,类型是Object
Object obj = iterator.next();
System.out.println("obj=" + obj);
}
}
}
class Book{
private String name;
private String author;
private double price;
public Book(String name, String author, double price) {
this.name = name;
this.author = author;
this.price = price;
}
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getAuthor() { return author; }
public void setAuthor(String author) { this.author = author; }
public double getPrice() { return price; }
public void setPrice(double price) { this.price = price; }
@Override
public String toString() {
return "Book{" +
"name='" + name + '\'' +
", author='" + author + '\'' +
", price=" + price +
'}';
}
}
===========控制台输出============
obj=Book{name='西游记', author='吴承恩', price=99.0}
obj=Book{name='小李飞刀', author='古龙', price=98.8}
obj=Book{name='红楼梦', author='曹雪芹', price=90.5}
---------第二次遍历---------
obj=Book{name='西游记', author='吴承恩', price=99.0}
obj=Book{name='小李飞刀', author='古龙', price=98.8}
obj=Book{name='红楼梦', author='曹雪芹', price=90.5}
Collection 接口遍历元素方式2 -for循环增强
增强for
循环,可以代替iterator
迭代器,特点:增强for
就是简化版的iterator
,本质是一样。只能用于遍历集合或者数组
基本语法:
for(元素类型 元素名 : 集合或数组名){
访问元素
}
代码演示:
public class CollectionFor {
@SuppressWarnings({"all"})
public static void main(String[] args) {
Collection collection = new ArrayList();
collection.add(new Book("西游记","吴承恩",99.0));
collection.add(new Book("小李飞刀","古龙",98.8));
collection.add(new Book("红楼梦","曹雪芹",90.5));
//1、使用增强for循环,Collection集合
//2、增强for,底层仍然是迭代器
//3、增强for可以理解成就是简化版本的 迭代器遍历
//4、快捷键方式 I
for(Object book : collection){
System.out.println("book=" + book);
}
//增强for,也可以直接在数组使用
int[] nums = {1,2,3};
for (int i : nums){
System.out.println("i=" + i);
}
}
}
===========控制台输出============
book=Book{name='西游记', author='吴承恩', price=99.0}
book=Book{name='小李飞刀', author='古龙', price=98.8}
book=Book{name='红楼梦', author='曹雪芹', price=90.5}
i=1
i=2
i=3
练习
请编写程序
1、创建 3个 Dog{naem, age}对象,放入到 ArrayList中,赋给 List 引用
2、用迭代器和增强for循环两种方式类遍历
3、重写Dog 的toString方法,输出name和age
public class CollectionExercise {
public static void main(String[] args) {
List list = new ArrayList<>();
list.add(new Dog("小黑",3));
list.add(new Dog("大黄",30));
list.add(new Dog("大壮",8));
//先使用for循环
System.out.println("--------使用for循环遍历-------");
for(Object dog : list){
System.out.println("dog=" + dog);
}
//使用迭代器
System.out.println("--------使用迭代器遍历-------");
Iterator iterator = list.iterator();
while (iterator.hasNext()) {
Object dog = iterator.next();
System.out.println("dog=" + dog);
}
}
}
/**
* 1、创建 3个 Dog{naem, age}对象,放入到 ArrayList中,赋给 List 引用
* 2、用迭代器和增强for循环两种方式类遍历
* 3、重写Dog 的toString方法,输出name和age
*/
class Dog{
private String name;
private int age;
public Dog(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public int getAge() { return age; }
public void setAge(int age) { this.age = age; }
@Override
public String toString() {
return "Dog{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
===========控制台输出============
--------使用for循环遍历-------
dog=Dog{name='小黑', age=3}
dog=Dog{name='大黄', age=30}
dog=Dog{name='大壮', age=8}
--------使用迭代器遍历-------
dog=Dog{name='小黑', age=3}
dog=Dog{name='大黄', age=30}
dog=Dog{name='大壮', age=8}
四、List
List接口
List接口基本介绍
List 接口是 Collection 接口的子接口
1)List集合类中元素有序(即添加顺序和取出顺序一致)、且可重复
2)List集合中的每个元素都有其对应的顺序索引,即支持索引
3)List容器中的元素都对应一个整型的序号记载其在容器中的位置,可以根据序号取容器的元素。
4)JDK API 中List接口的实现类有
常用的有: ArrayList、LinkedList和Vector
public class List_ {
@SuppressWarnings({"all"})
public static void main(String[] args) {
//1. List集合类中元素有序(即添加顺序和取出顺序一致)、且可重复
List list = new ArrayList();
list.add("jack");
list.add("tom");
list.add("mary");
list.add("zzp");
list.add("tom");
System.out.println("list=" + list);//[jack, tom, mary, zzp, tom]
//2. List集合中的每个元素都有其对应的顺序索引,即支持索引
// 索引是从0开始的
System.out.println(list.get(3));//zzp
}
}
List接口的常用方法
List 集合里添加了一些根据索引来操作集合元素的方法
变量和类型 | 方法 | 描述 |
---|---|---|
void | add(int index, E element) | 将指定元素插入此列表中的指定位置(可选操作) |
boolean | add(E e) | 将指定的元素追加到此列表的末尾(可选操作) |
boolean | addAll(int index, Collection<? extends E> c) | 将指定集合中的所有元素插入到指定位置的此列表中(可选操作) |
boolean | addAll(Collection<? extends E> c) | 将指定集合中的所有元素按指定集合的迭代器(可选操作)返回的顺序追加到此列表的末尾 |
void | clear() | 从此列表中删除所有元素(可选操作) |
boolean | contains(Object o) | 如果此列表包含指定的元素,则返回 true |
boolean | containsAll(Collection<?> c) | 如果此列表包含指定集合的所有元素,则返回 true |
boolean | equals(Object o) | 将指定对象与此列表进行比较以获得相等性 |
E | get(int index) | 返回此列表中指定位置的元素 |
int | hashCode() | 返回此列表的哈希码值 |
int | indexOf(Object o) | 返回此列表中第一次出现的指定元素的索引,如果此列表不包含该元素,则返回-1 |
int | lastIndexOf(Object o) | 返回此列表中指定元素最后一次出现的索引,如果此列表不包含该元素,则返回-1 |
E | remove(int index) | 删除此列表中指定位置的元素(可选操作) |
E | set(int index, E element) | 用指定的元素替换此列表中指定位置的元素(可选操作) |
int | size() | 返回此列表中的元素数 |
default void | sort(Comparator<? super E> c) | 根据指定的Comparator引发的顺序对此列表进行排序 |
List | subList(int fromIndex, int toIndex) | 返回指定的 fromIndex (包含)和 toIndex (不包括)之间的此列表部分的视图 |
public class ListMethod {
@SuppressWarnings({"all"})
public static void main(String[] args) {
List list = new ArrayList();
list.add("张三丰");
list.add("贾宝玉");
// void add(int index, Object ele);//在index位置插入ele元素
// 在index=1的位置插入一个对象
list.add(1,"zzp");
System.out.println("list=" + list);//[张三丰, zzp, 贾宝玉]
// boolean addAll(int index, Collection eles);//从index位置开始将eles中所有元素添加进来
List list2 = new ArrayList();
list2.add("jack");
list2.add("tom");
list.addAll(1,list2);
System.out.println("list=" + list);//[张三丰, jack, tom, zzp, 贾宝玉]
// Object get(int index);//获取指定index位置的元素
System.out.println(list.get(0));//张三丰
// int indexOf(Object obj);//返回obj在集合首次出现的位置
System.out.println(list.indexOf("tom"));//2
// int lastIndexOf(Object obj);//返回obj在当前集合中末次出现的位置
list.add("zzp");
System.out.println("list=" + list);//[张三丰, jack, tom, zzp, 贾宝玉, zzp]
System.out.println(list.lastIndexOf("zzp"));//5
// Object remove(int index);//移除指定index位置的元素,并返回此元素
list.remove(0);
System.out.println("list=" + list);//[jack, tom, zzp, 贾宝玉, zzp]
//Object set(int index, Object ele);//设置指定index位置的元素为ele,相当于替换
list.set(1,"玛丽");
System.out.println("list=" + list);//[jack, 玛丽, zzp, 贾宝玉, zzp]
// List subList(int fromIndex, int toIndex);//返回从fromIndex到toIndex位置的子集合
// 注意返回的子集合 fromIndex <= subList < toIndex
List returnList = list.subList(0, 2);
System.out.println("returnList=" + returnList);//[jack, 玛丽]
}
}
===========控制台输出============
list=[张三丰, zzp, 贾宝玉]
list=[张三丰, jack, tom, zzp, 贾宝玉]
张三丰
2
list=[张三丰, jack, tom, zzp, 贾宝玉, zzp]
5
list=[jack, tom, zzp, 贾宝玉, zzp]
list=[jack, 玛丽, zzp, 贾宝玉, zzp]
returnList=[jack, 玛丽]
List接口练习
添加10个以上的元素(比如String “hello”),在2号位插入一个元素 “zzp先生”,获取第5个元素,删除第6个元素,修改第7个元素,在使用迭代器遍历集合,要求:使用List的实现类ArrayList完成
public class ListExercise {
@SuppressWarnings({"all"})
public static void main(String[] args) {
/*
添加10个以上的元素(比如String “hello”),在2号位插入一个元素 “zzp先生”,
获取第5个元素,删除第6个元素,修改第7个元素,在使用迭代器遍历集合,
要求:使用List的实现类ArrayList完成
*/
List list = new ArrayList();
for (int i = 0; i < 12; i++) {
list.add("hello" + i);
}
System.out.println("list=" + list);
//在2号位插入一个元素 “zzp先生”
list.add(1,"zzp先生");
System.out.println("list=" + list);
//获取第5个元素
System.out.println("获取第5个元素=" + list.get(4));
//删除第6个元素
list.remove(list.get(5));
System.out.println("list=" + list);
//修改第7个元素
list.set(6,"西游记");
System.out.println("list=" + list);
//使用迭代器遍历集合
Iterator iterator = list.iterator();
while (iterator.hasNext()) {
Object obj = iterator.next();
System.out.println("obj=" + obj);
}
}
}
===========控制台输出============
list=[hello0, hello1, hello2, hello3, hello4, hello5, hello6, hello7, hello8, hello9, hello10, hello11]
list=[hello0, zzp先生, hello1, hello2, hello3, hello4, hello5, hello6, hello7, hello8, hello9, hello10, hello11]
获取第5个元素=hello3
list=[hello0, zzp先生, hello1, hello2, hello3, hello5, hello6, hello7, hello8, hello9, hello10, hello11]
list=[hello0, zzp先生, hello1, hello2, hello3, hello5, 西游记, hello7, hello8, hello9, hello10, hello11]
obj=hello0
obj=zzp先生
obj=hello1
obj=hello2
obj=hello3
obj=hello5
obj=西游记
obj=hello7
obj=hello8
obj=hello9
obj=hello10
obj=hello11
List的三种遍历方式[ArrayList、LinkedList、Vector]
方法一:使用 iterator
Iterator iter = col.interator();
while(iter.hasNext()){
Object obj = iter.next();
}
方法二:使用增强for
for(Object obj : col){
}
方法三:使用普通for
for(int i = 0; i < list.size(); i++){
Object obj = list.get(i);
System.out.println(obj);
}
代码演示:
public class ListFor {
@SuppressWarnings({"all"})
public static void main(String[] args) {
//List 接口的实现子类 Vector LinkedList ArrayList
List list = new ArrayList();
// List list = new LinkedList();
// List list = new Vector();
list.add("jack");
list.add("tom");
list.add("人生如戏");
list.add("酸甜排骨");
//遍历
System.out.println("-----迭代器-----");
// 1、迭代器
Iterator iterator = list.iterator();
while (iterator.hasNext()) {
Object obj = iterator.next();
System.out.println("obj=" + obj);
}
System.out.println("-----增强for-----");
// 2、增强for
for (Object o : list) {
System.out.println("o=" + o);
}
System.out.println("-----普通for-----");
// 3、普通for
for (int i = 0; i < list.size(); i++) {
System.out.println("对象=" + list.get(i));
}
}
}
===========控制台输出============
-----迭代器-----
obj=jack
obj=tom
obj=人生如戏
obj=酸甜排骨
-----增强for-----
o=jack
o=tom
o=人生如戏
o=酸甜排骨
-----普通for-----
对象=jack
对象=tom
对象=人生如戏
对象=酸甜排骨
List实现类的练习2
使用List实现类添加三本图书,并遍历,大于如下效果:
名称:XXX 价格:xxx 作者:XXX
名称:XXX 价格:xxx 作者:XXX
要求:
1)按价格排序,从低到高排序(使用冒泡法)
2)要求使用ArrayList、LinkedList和Vector三种集合实现
新建Book类:
public class Book {
private String name;
private String author;
private double price;
public Book(String name, String author, double price) {
this.name = name;
this.author = author;
this.price = price;
}
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getAuthor() { return author; }
public void setAuthor(String author) { this.author = author; }
public double getPrice() { return price; }
public void setPrice(double price) { this.price = price; }
@Override
public String toString() {
return "名称:"+name+"\t\t价格:"+price+"\t\t作者:"+author;
}
}
测试类:
@SuppressWarnings({"all"})
public class ListExercise02 {
public static void main(String[] args) {
List list = new ArrayList();
//List list = new Vector();
//List list = new LinkedList();
list.add(new Book("红楼梦","曹雪芹",51.9));
list.add(new Book("西游记","吴承恩",61.5));
list.add(new Book("水浒传","施耐庵",11.5));
//遍历
for (Object obj : list){
System.out.println(obj);
}
//冒泡排序
sort(list);
System.out.println("-----------排序-----------");
for (Object obj : list){
System.out.println(obj);
}
}
//静态方法 排序 价格从小到大
public static void sort(List list){
int size = list.size();
for (int i = 0; i < size - 1; i++) {
for (int j = 0; j < size - i - 1; j++) {
//取出对象
Book book1 = (Book)list.get(j);//向下转型
Book book2 = (Book)list.get(j + 1);
if(book1.getPrice() > book2.getPrice()){//交换
list.set(j,book2);
list.set(j +1,book1);
}
}
}
}
}
===========控制台输出============
名称:红楼梦 价格:51.9 作者:曹雪芹
名称:西游记 价格:61.5 作者:吴承恩
名称:水浒传 价格:11.5 作者:施耐庵
-----------排序-----------
名称:水浒传 价格:11.5 作者:施耐庵
名称:红楼梦 价格:51.9 作者:曹雪芹
名称:西游记 价格:61.5 作者:吴承恩
ArraysList
ArrayList底层结构和源码分析
1)permits all elements, including null
, ArrayList 可以加入null,并且多个
2)ArrayList 是有数组来实现数据存储的
3)ArrayList 基本等同于 Vector,除了 ArrayList是线程不安全(执行效率高)卡源码,在多线程情况下,不建议使用ArrayList
代码演示:
public class ArrayDetail {
@SuppressWarnings({"all"})
public static void main(String[] args) {
ArrayList arrayList = new ArrayList<>();
arrayList.add(null);
arrayList.add("tom");
arrayList.add(null);
System.out.println("arrayList=" + arrayList);//[null, tom, null]
}
}
ArrayList 是线程不安全的,看源码没有加synchronized
Vector 是线程安全的,看源码有加synchronized
ArrayList的底层操作机制源码分析(重点 )
1)ArrayList 中维护了一个 Object 类型的数组 elementData
。
transient Object[] elementDate;
// transient :表示瞬间,短暂的,表示该属性不会被序列化
2)当使用ArrayList对象时,如果使用的是无参构造器,则初始 elementData
容量为0,第一次添加,则扩容elementData
为10,如需要再次扩容elementData
为1.5倍
3)如果使用的是指定大小的构造器,则初始elementData
容量为指定大小,如果需要扩容,则直接扩容elementData
为1.5倍
ArrayList的底层操作机制案例
代码示例:
public class ArrayListSource {
@SuppressWarnings({"all"})
public static void main(String[] args) {
//解读源码
//使用有参构造器创建ArrayList对象
//ArrayList list = new ArrayList();
ArrayList list = new ArrayList(8);
//使用for给list添加 1-10数据
for (int i = 0; i < 10; i++) {
list.add(i);
}
//使用for给list添加 11-15数据
for (int i = 11; i <= 15; i++) {
list.add(i);
}
list.add(100);
list.add(200);
list.add(null);
}
}
源码:进入ArrayList构造器方法
public class ArrayList<E> extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{
....
/**
* Shared empty array instance used for empty instances.
*/
private static final Object[] EMPTY_ELEMENTDATA = {};
transient Object[] elementData; // non-private to simplify nested class access
/**
* 使用无参构造器,创建了一个空的 elementData数组
*/
public ArrayList() {
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
/**
* 使用有参构造器
* 创建一个指定大小elementData 数组
* this.elementData = new Object[initialCapacity];
*
*/
public ArrayList(int initialCapacity) {//initialCapacity=8
if (initialCapacity > 0) {//8>0 true
this.elementData = new Object[initialCapacity];//初始化容量
} else if (initialCapacity == 0) {
this.elementData = EMPTY_ELEMENTDATA;
} else {
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
}
}
...
}
源码:list.add()
方法:
public class ArrayList<E> extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{
....
/**
* (1) 先确定是否要扩容
* (2) 如果执行 赋值
*/
public boolean add(E e) {
ensureCapacityInternal(size + 1); //1、先确定是否要扩容
elementData[size++] = e;//2、执行赋值操作 先赋值 后++
return true;
}
/**
* 该方法确定minCapacity
* (1)第一次扩容10
*/
private void ensureCapacityInternal(int minCapacity) {
ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
}
//第一次扩容设置数组大小为10
private static int calculateCapacity(Object[] elementData, int minCapacity) {
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
return Math.max(DEFAULT_CAPACITY, minCapacity);
}
return minCapacity;
}
/**
* (1)modCount++ 记录集合修改的次数
* (2)如果elementData的大小不够,就调用grow()扩容
*/
private void ensureExplicitCapacity(int minCapacity) {
modCount++;
// 判断 数组是否要扩容 minCapacity数组最小的大小 elementData实际上数组大小
if (minCapacity - elementData.length > 0)
grow(minCapacity);//扩容
}
/*
* (1)真的扩容
* (2)使用扩容机制来要扩容到多大
* (3)第一次newCapacity = 10
* (4)第二次后及其以后,按照1.5扩容
* (5)扩容使用的是 Arrays.copyOf()
*/
private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
int newCapacity = oldCapacity + (oldCapacity >> 1);//oldCapacity >> 1=》除以2 实际是 1.5倍 但第一次扩容为0
if (newCapacity - minCapacity < 0)//补偿机制
newCapacity = minCapacity;//当newCapacity=0时,把minCapacity赋给newCapacity
if (newCapacity - MAX_ARRAY_SIZE > 0)
newCapacity = hugeCapacity(minCapacity);
// minCapacity is usually close to size, so this is a win:
elementData = Arrays.copyOf(elementData, newCapacity);//底层数组扩容
}
...
}
显示所有的debug详细详细,设置:
小总结:
如果是有参数的构造器,扩容机制
(1)第一次扩容,就按照elementData
的1.5倍扩容
(2)整个执行流程是和无参构造的流程一样
Vector
Vector底层结构和源码剖析
基本介绍
1)Vector类定义说明
public class Vector<E>
extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, java.io.Serializable{
protected Object[] elementData;
....
}
2)Vector 底层也是一个对象数组,protected Object[] elementData;
3)Vector 是线程同步的,即线程安全的,Vector类的操作方法有synchronized
public synchronized E get(int index) {
if (index >= elementCount)
throw new ArrayIndexOutOfBoundsException(index);
return elementData(index);
}
4)开发中,需要线程同步安全时,可以考虑使用 Vector
Vector 底层结构和 ArrayList 的比较
底层结构 | 版本 | 线程安全(同步)效率 | 扩容倍数 | |
---|---|---|---|---|
ArrayList | 可变数组 | jdk 1.2 | 不安全,效率高 | 如果有参构造 1.5 倍 如果是无参 1.第一次10 2.第二次开始1.5倍扩容 |
Vector | 可变数组 Object[] | jdk 1.0 | 安全,效率不高 | 如果是无参,默认10,满后,就按2倍扩容 如果指定大小,则每次直接按2倍扩容 |
代码示例:
public class Vector_ {
@SuppressWarnings({"all"})
public static void main(String[] args) {
//无参构造
Vector vector = new Vector();
//有参构造
// Vector vector = new Vector(8);
for (int i = 0; i < 10; i++) {
vector.add(i);
}
vector.add(99);
System.out.println("vector="+vector);
}
}
Vector 源码:
初始化流程:
package java.util;
public class Vector<E>
extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{
/**
* The array buffer into which the components of the vector are
* stored. The capacity of the vector is the length of this array buffer,
* and is at least large enough to contain all the vector's elements.
*
* <p>Any array elements following the last element in the Vector are null.
*
* @serial
*/
protected Object[] elementData;
protected int capacityIncrement;
...
/**
* Constructs an empty vector so that its internal data array
* has size {@code 10} and its standard capacity increment is
* zero.
*/
//1.无参构造,再调用有参构造默认给10
public Vector() {
this(10);
}
/**
* Constructs an empty vector with the specified initial capacity and
* with its capacity increment equal to zero.
*
* @param initialCapacity the initial capacity of the vector
* @throws IllegalArgumentException if the specified initial capacity
* is negative
*/
//有参构造器,指定大小容量
public Vector(int initialCapacity) {
this(initialCapacity, 0);
}
//有参构造初始化
public Vector(int initialCapacity, int capacityIncrement) {
super();
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
this.elementData = new Object[initialCapacity];
this.capacityIncrement = capacityIncrement;
}
....
}
add(E e)
方法:
package java.util;
public class Vector<E>
extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{
...
/**
* Appends the specified element to the end of this Vector.
*
* @param e element to be appended to this Vector
* @return {@code true} (as specified by {@link Collection#add})
* @since 1.2
*/
//下面这个方法就是添加数据到Vector集合
public synchronized boolean add(E e) {// e: 0
modCount++;//修改次数
ensureCapacityHelper(elementCount + 1);
elementData[elementCount++] = e;
return true;
}
/**
* This implements the unsynchronized semantics of ensureCapacity.
* Synchronized methods in this class can internally call this
* method for ensuring capacity without incurring the cost of an
* extra synchronization.
*
* @see #ensureCapacity(int)
*/
// 确定是否需要扩容 条件:minCapacity - elementData.length > 0
private void ensureCapacityHelper(int minCapacity) {//1
// overflow-conscious code
if (minCapacity - elementData.length > 0)// 1 - 10 fase
grow(minCapacity);
}
/**
* The amount by which the capacity of the vector is automatically
* incremented when its size becomes greater than its capacity. If
* the capacity increment is less than or equal to zero, the capacity
* of the vector is doubled each time it needs to grow.
*
* @serial
*/
protected int capacityIncrement;
//如果 需要的组数大小 不够用,就扩容,扩容算法
// int newCapacity = oldCapacity + ((capacityIncrement > 0) ?
// capacityIncrement : oldCapacity);
// 即:oldCapacity + oldCapacity----就是扩容两倍
private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;//原有容量值
int newCapacity = oldCapacity + ((capacityIncrement > 0) ?
capacityIncrement : oldCapacity);
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
if (newCapacity - MAX_ARRAY_SIZE > 0)
newCapacity = hugeCapacity(minCapacity);
elementData = Arrays.copyOf(elementData, newCapacity);//扩容
}
....
}
LinkedList
LinkedList 的全面说明
1)LinkedList 底层实现了双向链表和双端队列的特点
2)可以添加任意元素(元素可重复),包括null
3)线程不安全,没有实现同步
LinkedList 的底层操作机制
1)LinkedList
底层维护了一个双向链表
2)LinkedList
中维护了两个属性 first
和 last
分别指向 首节点和尾结点
3)每个节点(Node
对象),里面又维护了 prev
,next
,item
三个属性,其中通过 prev
指向前一个,通过 next
指向下一个。最终实现双向链表
4)所以 LinkedList
的元素的添加和删除,不是通过数组完成的,相对来说效率高。
源码LinkedList
:
package java.util;
...
public class LinkedList<E>
extends AbstractSequentialList<E>
implements List<E>, Deque<E>, Cloneable, java.io.Serializable
{
/**
* Pointer to first node.
* Invariant: (first == null && last == null) ||
* (first.prev == null && first.item != null)
*/
transient Node<E> first;
/**
* Pointer to last node.
* Invariant: (first == null && last == null) ||
* (last.next == null && last.item != null)
*/
transient Node<E> last;
private static class Node<E> {
E item;
Node<E> next;
Node<E> prev;
Node(Node<E> prev, E element, Node<E> next) {
this.item = element;
this.next = next;
this.prev = prev;
}
}
....
}
5)模拟一个简单的双向链表:
public class LinkedList01 {
public static void main(String[] args) {
//模拟一个简单的双向链表
Node jack = new Node("jack");
Node tom = new Node("tom");
Node xim = new Node("小明");
//连接三节点,形成双向链表
// jack -> tom -> xm
jack.next = tom;
tom.next = xim;
//xm -> tom -> jack
xim.pre = tom;
tom.pre = jack;
Node first = jack;//让first引用指向jack,就是双向链表的头节点
Node last = xim;//让last引用指向xim,就是双向链表的尾节点
//演示,从头到尾进行遍历
System.out.println("-------从头到尾进行遍历-------");
while (true){
if(first == null){
break;
}
//输出first信息
System.out.println(first);
first = first.next;
}
//演示,从尾到头进行遍历
System.out.println("-------从尾到头进行遍历-------");
while (true){
if(last == null){
break;
}
//输出last信息
System.out.println(last);
last = last.pre;
}
//演示链表的添加对象/数据
//在 tom -- xim 之中,插入一个对象 zhang
//1、先创建一个Node节点,name就是 zhang
Node zhang = new Node("zhang");
//下面就把 zhang 加入了双向链表了
zhang.pre = tom;
zhang.next = xim;
tom.next = zhang;
xim.pre = zhang;
//让first 再次指向jack
first = jack;//让first引用指向jack,就是双向链表的头节点
//演示,从头到尾进行遍历
System.out.println("-------zhang添加 从头到尾进行遍历-------");
while (true){
if(first == null){
break;
}
//输出frist信息
System.out.println(first);
first = first.next;
}
//让last 再次指向xim
last = xim;//让last引用指向xim,就是双向链表的尾节点
//演示,从尾到头进行遍历
System.out.println("-------从尾到头进行遍历-------");
while (true){
if(last == null){
break;
}
//输出last信息
System.out.println(last);
last = last.pre;
}
}
}
//定义一个 Node 类,Node 对象 表示双向链表的一个节点
class Node{
public Object item;//真正存放的数据
public Node next;//指向下一个节点
public Node pre;//指向前一个节点
public Node(Object name){
this.item = name;
}
@Override
public String toString(){
return "Node name=" + item;
}
}
==============控制台输出=================
-------从头到尾进行遍历-------
Node name=jack
Node name=tom
Node name=小明
-------从尾到头进行遍历-------
Node name=小明
Node name=tom
Node name=jack
-------zhang添加 从头到尾进行遍历-------
Node name=jack
Node name=tom
Node name=zhang
Node name=小明
-------从尾到头进行遍历-------
Node name=小明
Node name=zhang
Node name=tom
Node name=jack
LinkedList 的增删改查询案例
public class LinkedListCRUD {
public static void main(String[] args) {
LinkedList linkedList = new LinkedList();
linkedList.add(1);
linkedList.add(2);
linkedList.add(3);
System.out.println("linkedList=" + linkedList);
//删除节点
linkedList.remove();//默认删除第一个节点
//linkedList.remove(2);//删除指定元素
System.out.println("linkedList=" + linkedList);
//修改每个节点对象
linkedList.set(1,99);
System.out.println("linkedList=" + linkedList);
//得到某个节点对象
// get(1) 是得到双向链表的第二个对象
Object obj = linkedList.get(1);//获取下标位置
System.out.println("obj=" + obj);
//因为LinkedList 是 实现 List接口,遍历方式
System.out.println("--------LinkedList遍历迭代器--------");
Iterator iterator = linkedList.iterator();
while (iterator.hasNext()){
Object next = iterator.next();
System.out.println("next=" + next);
}
System.out.println("--------LinkedList遍历增强for--------");
for (Object o : linkedList){
System.out.println("o=" + o);
}
System.out.println("--------LinkedList遍历普通for--------");
for (int i=0;i<linkedList.size();i++){
System.out.println(linkedList.get(i));
}
}
}
==============控制台输出=================
linkedList=[1, 2, 3]
linkedList=[2, 3]
linkedList=[2, 99]
obj=99
--------LinkedList遍历迭代器--------
next=2
next=99
--------LinkedList遍历增强for--------
o=2
o=99
--------LinkedList遍历普通for--------
2
99
LinkedList 源码解析:
构造器:
package java.util;
public class LinkedList<E>
extends AbstractSequentialList<E>
implements List<E>, Deque<E>, Cloneable, java.io.Serializable
{
...
transient int size = 0;
/**
* Constructs an empty list.
*/
//LinkedList 的属性 first = null, last = null
public LinkedList() {
}
}
添加节点(add(E e)
):
package java.util;
...
public class LinkedList<E>
extends AbstractSequentialList<E>
implements List<E>, Deque<E>, Cloneable, java.io.Serializable
{
transient int size = 0;
/**
* Pointer to first node.
* Invariant: (first == null && last == null) ||
* (first.prev == null && first.item != null)
*/
transient Node<E> first;
/**
* Pointer to last node.
* Invariant: (first == null && last == null) ||
* (last.next == null && last.item != null)
*/
transient Node<E> last;
/**
* Constructs an empty list.
*/
// new LinkedList() 空数据
public LinkedList() {
}
/**
* Appends the specified element to the end of this list.
*
* <p>This method is equivalent to {@link #addLast}.
*
* @param e element to be appended to this list
* @return {@code true} (as specified by {@link Collection#add})
*/
// 执行 linkedList.add(1);
public boolean add(E e) {
linkLast(e);//添加到最后一个节点
return true;
}
/**
* Links e as last element.
*/
//将新的节点,加入双向链表的最后
void linkLast(E e) {
final Node<E> l = last;//last=null
final Node<E> newNode = new Node<>(l, e, null);//创建新的节点,还没加入链表
last = newNode;//指向第一个节点
if (l == null)
first = newNode;//指向第一个节点
else
l.next = newNode;
size++;//链长
modCount++;//修改次数
}
private static class Node<E> {
E item;
Node<E> next;
Node<E> prev;
Node(Node<E> prev, E element, Node<E> next) {
this.item = element;
this.next = next;
this.prev = prev;
}
}
}
源码:删除节点(linkedList.remove();//默认删除第一个节点
):
package java.util;
...
public class LinkedList<E>
extends AbstractSequentialList<E>
implements List<E>, Deque<E>, Cloneable, java.io.Serializable
{
transient int size = 0;
/**
* Pointer to first node.
* Invariant: (first == null && last == null) ||
* (first.prev == null && first.item != null)
*/
transient Node<E> first;
/**
* Pointer to last node.
* Invariant: (first == null && last == null) ||
* (last.next == null && last.item != null)
*/
transient Node<E> last;
/**
* Retrieves and removes the head (first element) of this list.
*
* @return the head of this list
* @throws NoSuchElementException if this list is empty
* @since 1.5
*/
//删除第一个节点 removeFirst()
public E remove() {
return removeFirst();
}
/**
* Removes and returns the first element from this list.
*
* @return the first element from this list
* @throws NoSuchElementException if this list is empty
*/
// 实际执行 unlinkFirst()
public E removeFirst() {
final Node<E> f = first;//先获取first的节点对象
if (f == null)
throw new NoSuchElementException();
return unlinkFirst(f);
}
/**
* Unlinks non-null first node f.
*/
// 执行 unlinkFirst , 将 f 指向的双向链表的第一个节点拿掉
private E unlinkFirst(Node<E> f) {
// assert f == first && f != null;
final E element = f.item;
final Node<E> next = f.next;
f.item = null;
f.next = null; // help GC
first = next;
if (next == null)
last = null;
else
next.prev = null;
size--;
modCount++;
return element;
}
}
ArrayList和LinkedList的比较
底层结构 | 增删效率 | 改查效率 | |
---|---|---|---|
ArrayList | 可变数组 | 较低 数组扩容 | 较高 |
LinkedList | 双向链表 | 较高,通过链表追加 | 较低 |
如何选择 ArrayList 和 LinkedList:
1)如果我们改查的操作多,选择ArrayList
2)如果我们增删的操作多,选择LinkedList
3)一般来说,在程序中,80%-90% 都是查询,因此大部分情况下会选择 ArrayList
4)在一个项目中,根据业务灵活选择,也可以能这样,一个模块使用的是ArrayList,另一个模板使用的是LinkedList,也就是说,要根据业务来进行选择
五、Set
Set接口
Set接口基本介绍
1)无序(添加和取出的顺序不一致),没有索引
2)不允许重复元素,所以最大包含一个null
3)JDK API 中 Set接口的实现有:
Set 接口的常用方法
和List接口一样,Set接口
也是Collection的子接口
,因此,常用方法和 Collection接口一样
Set 接口的遍历方式
同Collection的遍历方式一样,因为Set接口也是Collection接口的子类。
1、可以使用迭代器
2、增强for循环
3、不能使用索引的方式来获取
Set 接口的常用方法举例
public class SetMethod {
@SuppressWarnings({"all"})
public static void main(String[] args) {
//解读:
//1、以Set 接口的实现类 HashSet 来演示Set 接口的方法
//2、set 接口的实现类的对象(Set接口对象),不能存放重复的元素,可以添加一个null
//3、set 接口对象存放数据是无序的(即添加顺序和取出顺序不一致)
//4、注意:取出的顺序的顺序虽然不是添加的顺序,但是它是固定的
Set set = new HashSet();
set.add("tom");
set.add("lili");
set.add("tom");//重复
set.add("jack");
set.add(null);
set.add(null);//重复
for (int i = 0; i < 10; i++) {
System.out.println("set=" + set);//[null, tom, lili, jack]
}
// 遍历
//方式1:使用迭代器
System.out.println("---------迭代器---------");
Iterator iterator = set.iterator();
while (iterator.hasNext()){
Object obj = iterator.next();
System.out.println("obj=" + obj);
}
set.remove(null);
//方式2:增强for
System.out.println("---------增强for---------");
for (Object o: set){
System.out.println("o=" + o);
}
//set接口对象,不能通过索引获取
}
}
==============控制台输出=================
set=[null, tom, lili, jack]
set=[null, tom, lili, jack]
set=[null, tom, lili, jack]
set=[null, tom, lili, jack]
set=[null, tom, lili, jack]
set=[null, tom, lili, jack]
set=[null, tom, lili, jack]
set=[null, tom, lili, jack]
set=[null, tom, lili, jack]
set=[null, tom, lili, jack]
---------迭代器---------
obj=null
obj=tom
obj=lili
obj=jack
---------增强for---------
o=tom
o=lili
o=jack
HashSet
HashSet 的全部说明
1)HashSet实现了Set接口
2)HashSet
底层实际上是HashMap
package java.util;
...
public class HashSet<E>
extends AbstractSet<E>
implements Set<E>, Cloneable, java.io.Serializable
{
/**
* Constructs a new, empty set; the backing <tt>HashMap</tt> instance has
* default initial capacity (16) and load factor (0.75).
*/
public HashSet() {
map = new HashMap<>();
}
}
3)可以存放null值,但是只能有一个null
4)HshSet不保证元素是有序的,取决于hash后,再确定索引的结果(即:不保证存放元素的顺序和取出顺序一致)
5)不能有重复元素/对象。
public class HashSet_ {
public static void main(String[] args) {
//解读:
//1. 构造器走的源码
/*
public HashSet() {
map = new HashMap<>();
}
*/
//2. HashSet可以存放null,但是只能有一个null,即元素不能重复
HashSet hashSet = new HashSet();
hashSet.add(null);
hashSet.add(null);
System.out.println("hashSet=" + hashSet);//[null]
}
}
HashSet案例说明
@SuppressWarnings({"all"})
public class HashSet01 {
public static void main(String[] args) {
HashSet set = new HashSet();
//说明:
//1、在执行add方法后,会返回一个boolen值
//2、如果添加成功,返回true,否则是false
System.out.println(set.add("john"));//true
System.out.println(set.add("lucy"));//true
System.out.println(set.add("john"));//false
System.out.println(set.add("jack"));//true
System.out.println(set.add("rose"));//true
//3、可以通过 remove 指定删除哪个对象
set.remove("john");
System.out.println("set=" + set);//3个
set = new HashSet();
System.out.println("set=" + set);//0个
//4、HashSet 不能添加相同的元素/数据
set.add("lucy");//添加成功
set.add("lucy");//添加不了
set.add(new Dog("tom"));//true
set.add(new Dog("tom"));//true
System.out.println("set=" + set);
//在加深一下,非常经典的面试题
set.add(new String("zzp"));//true
set.add(new String("zzp"));//添加不了
System.out.println("set=" + set);
}
}
class Dog{//定义了Dog类
private String name;
public Dog(String name) {
this.name = name;
}
@Override
public java.lang.String toString() {
return "Dog{" +
"name=" + name +
'}';
}
}
==============控制台输出=================
true
true
false
true
true
set=[rose, lucy, jack]
set=[]
set=[Dog{name=tom}, Dog{name=tom}, lucy]
set=[zzp, Dog{name=tom}, Dog{name=tom}, lucy]
HashSet底层机制说明(重要)
分析HashSet
底层是HashMap
,HashMap
底层是(数组 + 链表 + 红黑树)
演示(简单的 数组 + 链表)
public class HashSetStructure {
public static void main(String[] args) {
//模拟一个HashSet底层(HashMap 的底层结构 )
//1、创建一个数组,数组的类型是 Node[]
//2、有些人,直接把 Node[] 数组称为 表(table)
Node[] table = new Node[16];
//3、创建节点
Node john = new Node("john",null);
table[2] = john;
Node jack = new Node("jack",null);
john.next = jack; // 将jack 节点挂载到john
Node rose = new Node("rose",null);
jack.next = rose;// 将rose 节点挂载到jack
Node lucy = new Node("lucy",null);
table[3] = lucy;// 把lucy 放到 table表的索引为3的位置
System.out.println("table=" + table);
}
}
class Node{//节点,存储数据,可以指向下一个节点,从而形成链表
Object item; //存储数据
Node next;//指向下一个节点
public Node(Object item, Node next) {
this.item = item;
this.next = next;
}
@Override
public String toString() {
return "Node{" +
"item=" + item +
", next=" + next +
'}';
}
}
debug断点截图:
分析HashSet的添加元素底层是如何实现(hash() + equals()
)
1、HashSet
底层是 HashMap
2、添加一个元素时,先得到hash值
(会转成 ->索引值)
3、找到存储数据表table
,看这个索引位置是否已经存放的有元素
4、如果没有,直接加入
5、如果有,调用 equals
比较,如果相同,就放弃添加,如果不同,则添加到最后
6、在Java8中,如果一个链表的元素个数到达 TREEIFY_THRESHOLD
(默认是 8 ),并且table的大小 >= MIN_TREEIFY_CAPACITY
(默认 64),就会进行树化
(红黑树)
HashSet源码解读1
代码演示:
@SuppressWarnings({"all"})
public class HashSetSource {
public static void main(String[] args) {
HashSet hashSet = new HashSet();
hashSet.add("java");
hashSet.add("php");
hashSet.add("java");
System.out.println("set=" + hashSet);
}
}
对HashSet 的源码解读:
package java.util;
public class HashSet<E>
extends AbstractSet<E>
implements Set<E>, Cloneable, java.io.Serializable
{
...
// Dummy value to associate with an Object in the backing Map
private static final Object PRESENT = new Object();
transient Node<K,V>[] table;
// HashMap类
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
static final float DEFAULT_LOAD_FACTOR = 0.75f;
//主要是HashMap子类实现(有序链表)
void afterNodeInsertion(boolean evict) { }
void afterNodeAccess(Node<K,V> p) { }
void afterNodeRemoval(Node<K,V> p) { }
//1、执行构造器,new HashSet(); 底层就是HashMap
public HashSet() {
map = new HashMap<>();
}
// 2、执行add() 添加
public boolean add(E e) {//e 泛型(这是字符串常量 “java”)
return map.put(e, PRESENT)==null;//PRESENT(占位) = private static final Object PRESENT = new Object();
}
//3、执行put方法,该方法会执行hash(key)得到key对应的hash值 算法:h = key.hashCode()) ^ (h >>> 16) --> 避免hash碰撞
public V put(K key, V value) {//key=java value=PRESENT(static fina Object 共享的)
return putVal(hash(key), key, value, false, true);
}
//求hash值 按位异或 h 无符号 右移16位
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
//4、****核心方法****
// putVal
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;//定义了辅助变量
// table 就是 HashMap 的一个数组,类型是 Node[]
// if 语句表示如果当前table 是null,或者 大小=0
// 就第一次扩容,到16个空间。
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
// (1)根据key,得到hash,去计算该key应该存放到table表的哪个索引位置
//并且把这个位置的对象,赋值给 p
//(2)判断p,是否为null
//(2.1)如果p,为null,表示还没有存放元素,,就创建一个个Node (key="java",vlaue=PRESENT)
//(2.2) 就放在该位置 tab[i] = newNode(hash, key, value, null);
if ((p = tab[i = (n - 1) & hash]) == null) // true
tab[i] = newNode(hash, key, value, null);// 赋值数组 Node[]
else {
Node<K,V> e; K k;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;//修改次数
if (++size > threshold)//判断size(数组大小) 是否大于数组临界值 12
resize();//扩容
afterNodeInsertion(evict);//为子类实现的方法
return null;//返回null 代表添加数据成功
}
//HashMap.resize() 初始化/扩容table大小
final Node<K,V>[] resize() {
Node<K,V>[] oldTab = table;
int oldCap = (oldTab == null) ? 0 : oldTab.length;
int oldThr = threshold;
int newCap, newThr = 0;
if (oldCap > 0) {
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return oldTab;
}
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
newThr = oldThr << 1; // double threshold
}
else if (oldThr > 0) // initial capacity was placed in threshold
newCap = oldThr;
else { // zero initial threshold signifies using defaults
newCap = DEFAULT_INITIAL_CAPACITY;//默认16 容量
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);//临界值(负载因子*默认值16 = 12)
}
if (newThr == 0) {
float ft = (float)newCap * loadFactor;
newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
(int)ft : Integer.MAX_VALUE);
}
threshold = newThr;//临界值
@SuppressWarnings({"rawtypes","unchecked"})
Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];//创建节点
table = newTab;//赋值给table
if (oldTab != null) {
for (int j = 0; j < oldCap; ++j) {
Node<K,V> e;
if ((e = oldTab[j]) != null) {
oldTab[j] = null;
if (e.next == null)
newTab[e.hash & (newCap - 1)] = e;
else if (e instanceof TreeNode)
((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
else { // preserve order
Node<K,V> loHead = null, loTail = null;
Node<K,V> hiHead = null, hiTail = null;
Node<K,V> next;
do {
next = e.next;
if ((e.hash & oldCap) == 0) {
if (loTail == null)
loHead = e;
else
loTail.next = e;
loTail = e;
}
else {
if (hiTail == null)
hiHead = e;
else
hiTail.next = e;
hiTail = e;
}
} while ((e = next) != null);
if (loTail != null) {
loTail.next = null;
newTab[j] = loHead;
}
if (hiTail != null) {
hiTail.next = null;
newTab[j + oldCap] = hiHead;
}
}
}
}
}
return newTab;
}
// HashMap.Node 节点
static class Node<K,V> implements Map.Entry<K,V> {
final int hash;
final K key;
V value;
Node<K,V> next;
Node(int hash, K key, V value, Node<K,V> next) {
this.hash = hash;
this.key = key;
this.value = value;
this.next = next;
}
public final K getKey() { return key; }
public final V getValue() { return value; }
public final String toString() { return key + "=" + value; }
public final int hashCode() {
return Objects.hashCode(key) ^ Objects.hashCode(value);
}
public final V setValue(V newValue) {
V oldValue = value;
value = newValue;
return oldValue;
}
public final boolean equals(Object o) {
if (o == this)
return true;
if (o instanceof Map.Entry) {
Map.Entry<?,?> e = (Map.Entry<?,?>)o;
if (Objects.equals(key, e.getKey()) &&
Objects.equals(value, e.getValue()))
return true;
}
return false;
}
}
}
debug:hashSet.add("java");
第一次执行
执行构造器:
执行add() 添加
执行put方法,该方法会执行hash(key)得到key对应的hash值
获取hash值
核心方法
第一次扩容操作
扩容
判断数组的索引是否为空,为空直接添加key
HashSet源码解读2
hashSet.add("php");
第二次执行
hashSet.add("java");
第三次执行
package java.util;
public class HashSet<E>
extends AbstractSet<E>
implements Set<E>, Cloneable, java.io.Serializable
{
...
// Dummy value to associate with an Object in the backing Map
private static final Object PRESENT = new Object();
transient Node<K,V>[] table;
// HashMap类
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
static final float DEFAULT_LOAD_FACTOR = 0.75f;
//4、****核心方法****
// putVal
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;//定义了辅助变量
// table 就是 HashMap 的一个数组,类型是 Node[]
// if 语句表示如果当前table 是null,或者 大小=0
// 就第一次扩容,到16个空间。
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
// (1)根据key,得到hash,去计算该key应该存放到table表的哪个索引位置
//并且把这个位置的对象,赋值给 p
//(2)判断p,是否为null
//(2.1)如果p,为null,表示还没有存放元素,,就创建一个个Node (key="java",vlaue=PRESENT)
//(2.2) 就放在该位置 tab[i] = newNode(hash, key, value, null);
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
//一个开发技巧提示:在需要局部变量(赋值变量)时候,再创建
Node<K,V> e; K k;//辅助变量
//p.hash == hash:如果当前索引位置对应的链表的第一个元素和准备添加的key的hash值一样
//并且满足 下面两个条件之一:
//(1)(k = p.key) == key:准备加入的key 和 p 指向的Node节点的 key 是同一个对象
//(2)(key != null && key.equals(k)):p 指向的Node节点的 key 的equals()方法和准备加入的key比较后相同
//就不能加入(重复元素)
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
//再判断 p 是不是一颗红黑树,
//如果是一颗红黑树,就调用 putTreeVal(),来进行添加
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {//如果table对应索引位置,已经是一个链表,就使用for循环比较
//(1)依次和该链表的每个元素比较后,都不相同,则加入到该链表的最后 ==> (e = p.next) == null
// 注意:在把元素添加到链表后,立即判断 该链表是否已经达到8个节点
// ,就调用 treeifyBin() 对当前这个链表进行树化(转成红黑树)
// 注意,在转成红黑树,要进行判断,判断条件如下
// if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY(64))
// resize();
// 如果上面条件成立,先table扩容
// 如果上面条件不成立时,才进行转成红黑树
//(2)依次和该链表的每个元素比较过程中,如果有相同的情况下,就直接break ==> e.hash == hash....&&..
for (int binCount = 0; ; ++binCount) {//无限循环
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
if (binCount >= TREEIFY_THRESHOLD(8) - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
if (++size > threshold)
resize();//扩容
afterNodeInsertion(evict);
return null;
}
//红黑树
final void treeifyBin(Node<K,V>[] tab, int hash) {
int n, index; Node<K,V> e;
if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
resize();//扩容
else if ((e = tab[index = (n - 1) & hash]) != null) {
TreeNode<K,V> hd = null, tl = null;
do {
TreeNode<K,V> p = replacementTreeNode(e, null);
if (tl == null)
hd = p;
else {
p.prev = tl;
tl.next = p;
}
tl = p;
} while ((e = e.next) != null);
if ((tab[index] = hd) != null)
hd.treeify(tab);
}
}
}
HashSet源码解读3
分析HashSet的扩容和转成红黑树机制
1、HashSet
底层是HashMap
,第一次添加时,table
数组扩容到 16,临界值(threshold
)是 16*加载因子(loadFactor)是 0.75 = 12
2、如果table
数组使用到了临界值 12,就会扩容到 16*2=32,新的临界值就是 32*0.75 = 24,依次类推
3、在Java8中,如果一条链表的元素个数到达 TREEIFY_THRESHOLD
(默认是 8),并且table的大小 >= MIN_TREEIFY_CAPACITY
(默认64),就会进行树化(红黑树),否则仍然采用数组扩容机制
@SuppressWarnings({"all"})
public class HashSetIncrement {
public static void main(String[] args) {
/*
1、HashSet底层是HashMap,第一次添加时,table 数组扩容到 16,
临界值(threshold)是 16*加载因子(loadFactor)是 0.75 = 12
2、如果table 数组使用到了临界值 12,就会扩容到 16*2=32,
新的临界值就是 32*0.75 = 24,依次类推
*/
HashSet hashSet = new HashSet();
for (int i = 1; i <= 100; i++) {
hashSet.add(i);//1,2,3,4,5...100
}
}
}
debug执行:
第一次添加时,table 数组扩容到 16,临界值(threshold)是 16*加载因子(loadFactor)是 0.75 = 12
如果table 数组使用到了临界值 12,就会扩容到 162=32,新的临界值就是 320.75 = 24,依次类推
在Java8中,如果一条链表的元素个数到达 TREEIFY_THRESHOLD
(默认是 8),并且table的大小 >= MIN_TREEIFY_CAPACITY
(默认64),就会进行树化(红黑树),否则仍然采用数组扩容机制
代码演示:
@SuppressWarnings({"all"})
public class HashSetIncrement {
public static void main(String[] args) {
HashSet hashSet = new HashSet();
/*
在Java8中,如果一条链表的元素个数到达 TREEIFY_THRESHOLD(默认是 8),
并且table的大小 >= MIN_TREEIFY_CAPACITY(默认64),就会进行树化(红黑树),否则仍然采用数组扩容机制
*/
for (int i = 1; i <= 12; i++) {
hashSet.add(new A(i));//equals() 不同
}
System.out.println("hashSet=" + hashSet);
}
}
class A{
private int a;
public A(int n){
this.a = n;
}
//设置返回hash值是一样的 让HashSet产生链表
@Override
public int hashCode() {
return 100;
}
}
dubug执行:
size=1时,数组=16
size=9时,数组扩容到32
size=10时,数组扩容到64,索引位置变成36
size=11时,索引位置36的Node变成TreeNode(树化)
HashSet源码解读4
扩容源码判断:
//size 就是我们没加入一个节点Node(k, v, h, next) size ++
if (++size > threshold)
resize();//扩容
代码演示:
@SuppressWarnings({"all"})
public class HashSetIncrement {
public static void main(String[] args) {
HashSet hashSet = new HashSet();
/*
当我们向hashset增加一个元素, -> Node -> 加入table,就算是增加了一个 size++
*/
for (int i = 1; i <= 7; i++) {//在table的某一条链表上添加了 7个A对象
hashSet.add(new A(i));//equals() 不同
}
for (int i = 1; i <= 7; i++) {//在table的另外一条链表上添加了 7个B对象
hashSet.add(new B(i));//equals() 不同
}
System.out.println("hashSet=" + hashSet);
}
}
class B{
private int n;
public B(int n) {
this.n = n;
}
@Override
public int hashCode() { return 200; }
}
class A{
private int a;
public A(int n){
this.a = n;
}
//设置返回hash值是一样的 让HashSet产生链表
@Override
public int hashCode() { return 100; }
}
debug执行:
当size=12时:由于两个的hash索引不同,在table数组不同的位置,不在一条链表中
当size>12时,触发数组扩容,table=32
HashSet练习
1、定义一个Employee类,该类包含: private成员属性 name,age 要求:
1.创建3个Employee对象放入 HashSet中
2.当 name 和age的值相同时,认为是相同员工,不能添加到HashSet集合中
快速生成构造器、getset方法等,快捷键:Alt + Insert
/**
* 定义一个Employee类,该类包含: private成员属性 name,age 要求:
* 1.创建3个Employee对象放入 HashSet中
* 2.当 name 和age的值相同时,认为是相同员工,不能添加到HashSet集合中
*/
public class HashSetExercise {
public static void main(String[] args) {
HashSet hashSet = new HashSet();
hashSet.add(new Employee("milan",18));//ok
hashSet.add(new Employee("smith",18));//ok
hashSet.add(new Employee("milan",18));//false
System.out.println("hashSet=" + hashSet);//[{name='milan', age=18}, {name='smith', age=18}]
}
}
//创建Employee类
class Employee{
private String name;
private int age;
//如果name和age的值相同,则返回相同的hash值
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
Employee employee = (Employee) o;
return age == employee.age && Objects.equals(name, employee.name);
}
@Override
public int hashCode() {
return Objects.hash(name, age);
}
public Employee(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public int getAge() { return age; }
public void setAge(int age) { this.age = age; }
@Override
public String toString() {
return "{" + "name='" + name + '\'' + ", age=" + age + '}';
}
}
2、定义一个Employee类,该类包含:private成员属性name,sal,birthday(MyDate类型),其中 birthday 为 MyDate类型(属性包括:year,month,day),要求:
1.创建3个 Employee对象放入 HashSet中
2.当 name 和birthday的值相同时,认为是相同员工,不能添加到HashSet集合中
Employee类(MyDate类)
public class Employee {
private String name;
private int sal;
private MyDate birthday;
public Employee(String name, int sal, MyDate birthday) {
this.name = name;
this.sal = sal;
this.birthday = birthday;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
Employee employee = (Employee) o;
return Objects.equals(name, employee.name) && Objects.equals(birthday, employee.birthday);
}
@Override
public int hashCode() {
return Objects.hash(name, birthday);
}
@Override
public String toString() {
return "Employee{" +
"name='" + name + '\'' +
", sal=" + sal +
", birthday=" + birthday +
'}';
}
}
class MyDate{
private String year;
private String month;
private String day;
public MyDate(String year, String month, String day) {
this.year = year;
this.month = month;
this.day = day;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
MyDate myDate = (MyDate) o;
return Objects.equals(year, myDate.year) && Objects.equals(month, myDate.month) && Objects.equals(day, myDate.day);
}
@Override
public int hashCode() {
return Objects.hash(year, month, day);
}
@Override
public String toString() {
return "MyDate{" +
"year='" + year + '\'' +
", month='" + month + '\'' +
", day='" + day + '\'' +
'}';
}
}
执行类(main方法)
public class HashSetExercise02 {
public static void main(String[] args) {
HashSet hashSet = new HashSet();
hashSet.add(new Employee("xiaowang",18,new MyDate("2001","10","01")));
hashSet.add(new Employee("laozhang",30,new MyDate("1990","02","01")));
hashSet.add(new Employee("xiaowang",18,new MyDate("2001","10","01")));
System.out.println("hashSet.size()=" + hashSet.size());
System.out.println("hashSet=" + hashSet);
}
}
==============控制台输出=================
hashSet.size()=2
hashSet=[Employee{name='xiaowang', sal=18, birthday=MyDate{year='2001', month='10', day='01'}}, Employee{name='laozhang', sal=30, birthday=MyDate{year='1990', month='02', day='01'}}]
LinkedHashSet
LinkedHashSet 的全面说明
1)LinkedHashSet
是 HashSet
的子类
LinkedHashSet
源码类:
package java.util;
public class LinkedHashSet<E>
extends HashSet<E>
implements Set<E>, Cloneable, java.io.Serializable {...}
2)LinkedHashSet
底层是一个LinkedHashMap
,底层维护了一个 数组 + 双向链表
3)LinkedHashSet
根据元素的 hashCode
值来决定元素的存储位置,同时使用链表维护元素的次序(图),这使得元素看起来是以插入顺序保存的。
4)LinkedHashSet
不允许添加重复元素
LinkedHashSet源码解读
说明:
1、在 LinkedHashSet
中维护了一个hash
表和双向链表(LinkedHashSet
有 head
和 tail
)
2、每一个节点 有 pre
和 next
属性,这样可以形成双向链表
3、在添加一个元素时,先求hash
值,在求索引,确定该元素在hashtable
的位置,然后将添加的元素加入到双向链表(如果已经存在,不添加【原则和hashset
一样】)
tail.next = newElement;// 示意代码
newElement = tail
tail = newElement;
4、这样的话,我们遍历LinkeHashSet
也能确保插入顺序和遍历顺序一致
代码演示:
@SuppressWarnings({"all"})
public class LinkedHashSetSource {
public static void main(String[] args) {
//分析一下LinkedHashSet的底层机制
Set set = new LinkedHashSet();
set.add(new String("AA"));
set.add(456);
set.add(456);
set.add(new Customer("刘",101));
set.add(123);
set.add("zzp");
System.out.println("set=" + set);//[AA, 456, com.zzpedu.set_.Customer@1b6d3586, 123, zzp]
//解读:
//1. LinkedHashSet 加入顺序和取出元素/数据的顺序一致
//2. LinkedHashSet 底层维护的是一个 LinkedHashMap(是HashMap的子类)
//3. LinkedHashSet 底层结构 (数组table+双向链表)
//4. 添加第一次时,直接将 数组table 扩容到 16,存放的节点类型 LinkedHashMap$Entry
//5. 数组 HashMap$Node[] 存放的元素数据是 LinkedHashMap$Entry类型
/*
//继承关系是在内存类完成
static class Entry<K,V> extends HashMap.Node<K,V> {
Entry<K,V> before, after;
Entry(int hash, K key, V value, Node<K,V> next) {
super(hash, key, value, next);
}
}
*/
}
}
class Customer{
private String name;
private int no;
public Customer(String name, int no) {
this.name = name;
this.no = no;
}
}
源码解读:
1、LinkedHashSet
加入顺序和取出元素/数据的顺序一致
2、LinkedHashSet
底层维护的是一个 LinkedHashMap
(是HashMap
的子类)
3、LinkedHashSet
底层结构 (数组+双向链表)
4、添加第一次时,直接将 数组table
扩容到 16,存放的节点类型 LinkedHashMap$Entry
5、数组 HashMap$Node[]
存放的元素/数据是 LinkedHashMap$Entry
类型
源码示例:
package java.util;
public class LinkedHashSet<E>
extends HashSet<E>
implements Set<E>, Cloneable, java.io.Serializable {
//LinkedHashSet构造器,默认初始化数组容量16,负载因子0.75
public LinkedHashSet() {
super(16, .75f, true);
}
//HashSet<E>类的构造器
HashSet(int initialCapacity, float loadFactor, boolean dummy) {
map = new LinkedHashMap<>(initialCapacity, loadFactor);
}
/**
* HashMap.Node subclass for normal LinkedHashMap entries.
*/
//LinkedHashMap类的Entry静态类
//继承关系是在内部类完成
static class Entry<K,V> extends HashMap.Node<K,V> {
Entry<K,V> before, after;
Entry(int hash, K key, V value, Node<K,V> next) {
super(hash, key, value, next);
}
}
//HashSet类的add
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
}
LinkedHashSet练习题
要求:Car类(属性name,price),如果name 和 price 一样,
则认为相同元素,就不能添加
@SuppressWarnings({"all"})
public class LinkedHashSetExercise {
public static void main(String[] args) {
LinkedHashSet linkedHashSet = new LinkedHashSet();
linkedHashSet.add(new Car("奥迪",1000));
linkedHashSet.add(new Car("法拉利",30000));
linkedHashSet.add(new Car("奥迪",1000));
linkedHashSet.add(new Car("保时捷",700000));
linkedHashSet.add(new Car("奥迪",1000));
System.out.println("linkedHashSet=" + linkedHashSet);
}
}
/**
* 要求:Car类(属性name,price),如果name 和 price 一样,
* 则认为相同元素,就不能添加
*/
class Car{
private String name;
private int price;
//重写equals 方法 和 hashCode 方法
//当name和price相同时,就返回相同的的 hashCode值,equals返回true
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
Car car = (Car) o;
return price == car.price && Objects.equals(name, car.name);
}
@Override
public int hashCode() {
return Objects.hash(name, price);
}
public Car(String name, int price) {
this.name = name;
this.price = price;
}
@Override
public String toString() {
return "\nCar{" +
"name='" + name + '\'' +
", price=" + price +
'}';
}
}
==============控制台输出=================
linkedHashSet=[
Car{name='奥迪', price=1000},
Car{name='法拉利', price=30000},
Car{name='保时捷', price=700000}]
TreeSet
代码演示:
@SuppressWarnings({"all"})
public class TreeSetDemo {
public static void main(String[] args) {
//解读:
//1.当我们使用无参构造器,创建TreeSet时,仍然是无序的
//2.希望添加的元素,按照字符串大小来排序
//3.使用TreeSet 提供的一个构造器,可以传入一个比较器(匿名内部类)
// 并指定排序的规则
// TreeSet treeSet = new TreeSet();
TreeSet treeSet = new TreeSet(new Comparator() {
@Override
public int compare(Object o1, Object o2) {
// 下面 调用String的 compareTo方法进行字符串大小比较
// return ((String) o1).compareTo((String) o2);
//如果要求加入的元素,按照长度大小排序
return String.valueOf(o1).length() - String.valueOf(o2).length();
}
});
//添加数据
treeSet.add("jack");
treeSet.add("tom");
treeSet.add("sp");
treeSet.add("zzp");//加不了 因为构造器传入compare是长度相比较 之前加了tom的长度size
//System.out.println("treeSet=" + treeSet);//treeSet=[jack, sp, tom, zzp]
System.out.println("treeSet=" + treeSet);//treeSet=[sp, tom, jack]
//源码解读:
/*
1. 构造器把传入的比较器(comparator)对象,
赋给了 TreeSet的底层TreeMap的属性this.comparator = comparator
public TreeSet(Comparator<? super E> comparator) {
this(new TreeMap<>(comparator));//底层是TreeMap
}
2. 在调用 treeSet.add("xxx"),在底层会执行到下面语句
if (cpr != null) {// cpr 就是我们的匿名内部类(对象)
do {
parent = t;
//底层比较方法调用 Comparator接口类的 int compare(T o1, T o2); 方法
//动态的绑定到我们的匿名内部类(对象)compare
cmp = cpr.compare(key, t.key);
if (cmp < 0)
t = t.left;
else if (cmp > 0)
t = t.right;
else //如果相等,即返回0,这个key就没有加入
return t.setValue(value);
} while (t != null);
}
*/
}
}
TreeSet源码示例:
package java.util;
public class TreeSet<E> extends AbstractSet<E>
implements NavigableSet<E>, Cloneable, java.io.Serializable
{
private static final Object PRESENT = new Object();
//TreeMap类
private final Comparator<? super K> comparator;
//1.构造器把传入的比较器(comparator)对象,
// 赋给了 TreeSet的底层TreeMap的属性this.comparator = comparator
public TreeSet(Comparator<? super E> comparator) {
this(new TreeMap<>(comparator));//底层是TreeMap
}
//把传入的comparator 赋值给它的属性
public TreeMap(Comparator<? super K> comparator) {
this.comparator = comparator;
}
public boolean add(E e) {
return m.put(e, PRESENT)==null;
}
//TreeMap类 真正的添加元素 treeSet.add();
public V put(K key, V value) {
Entry<K,V> t = root;
if (t == null) {
compare(key, key); // type (and possibly null) check
root = new Entry<>(key, value, null);
size = 1;
modCount++;
return null;
}
int cmp;
Entry<K,V> parent;
// split comparator and comparable paths
Comparator<? super K> cpr = comparator;//比较器
if (cpr != null) {// cpr 就是我们的匿名内部类(对象)
do {
parent = t;
// 底层比较方法调用 Comparator接口类的 int compare(T o1, T o2); 方法
cmp = cpr.compare(key, t.key);//动态的绑定到我们的匿名内部类(对象)compare
if (cmp < 0)
t = t.left;
else if (cmp > 0)
t = t.right;
else //如果相等,即返回0,这个key就没有加入
return t.setValue(value);
} while (t != null);
}
else {
if (key == null)
throw new NullPointerException();
@SuppressWarnings("unchecked")
Comparable<? super K> k = (Comparable<? super K>) key;
do {
parent = t;
cmp = k.compareTo(t.key);
if (cmp < 0)
t = t.left;
else if (cmp > 0)
t = t.right;
else
return t.setValue(value);
} while (t != null);
}
Entry<K,V> e = new Entry<>(key, value, parent);
if (cmp < 0)
parent.left = e;
else
parent.right = e;
fixAfterInsertion(e);
size++;
modCount++;
return null;
}
}
六、Map
Map体系图:
Map接口
Map接口实现类的特点
注意:这里讲的是 JDK8
的Map
接口特点
1)Map
与Collection
并列存在,用于保存具有映射关系的数据:Key-Value
2)Map
中的 key
和 value
可以是任何引用类型的数据,会封装到 HashMap$Node
对象中
3)Map
中的 key
不允许重复,原因和HashSet
一样
4)Map
中的 value
可以重复
5)Map
的key
可以为null
,value
也可以为null
,注意 key
为null
,只能有一个,value
为null
,可以为多个
6)常用String类
作为Map
的 key
7)key
和 value
之间存在单向一对一关系,即通过指定的 key
总能找到对应的 value
@SuppressWarnings({"all"})
public class Map_ {
public static void main(String[] args) {
//Map接口实现类的特点,使用实现类HashMap
//1、Map与Collection并列存在,用于保存具有映射关系的数据:Key-Value(双列元素)
//2、Map 中的 key 和 value 可以是任何引用类型的数据,会封装到 HashMap$Node 对象中
//3、Map 中的 key 不允许重复,原因和HashSet 一样
//4、Map 中的 value 可以重复
//5、Map 的key 可以为null,value 也可以为null,注意 key 为null,只能有一个,value 为null,可以为多个
//6、常用String类作为Map的 key
//7、key 和 value 之间存在单向一对一关系,即通过指定的 key 总能找到对应的 value
HashMap map = new HashMap<>();
map.put("no1","张三");//k-v
map.put("no2","李四");//k-v
map.put("no1","张小二");//当有相同k,就等价于替换。
map.put("no3","张小二");//k-v
map.put(null,null);//k-v
map.put(null,"abc");//等价替换
map.put("no4",null);//k-v
map.put("no5",null);//k-v
map.put(5,"王五");//k-v
map.put(new Object(),"赵六");//k-v
System.out.println("map=" + map);
// 通过get,传入 key,会返回对应的value
System.out.println(map.get("no2"));//李四
}
}
==============控制台输出=================
map={no2=李四, null=abc, no1=张小二, no4=null, no3=张小二, no5=null, 5=王五, java.lang.Object@1b6d3586=赵六}
李四
Map接口特点
Map
存放数据的key-value
示意图,一对 k-v
是放在一个Node
中的,有因为HashMap$Node
实现 Entry
接口,有些书上也说 一对 k-v
就是一个 Entry
代码演示:
@SuppressWarnings({"all"})
public class MapSource {
public static void main(String[] args) {
HashMap map = new HashMap<>();
map.put("no1","张三");//k-v
map.put("no2","李四");//k-v
map.put(new Car(),new Person());//k-v
//解读:
//1. k-v 最后是 HashMap$Node node = newNode(hash, key, value, null)
//2. k-v 为了方便程序员的遍历,还会 创建 EntrySet 集合,该集合存放的元素的类型 Entry,
// 而一个 Entry 对象就包含 k,v EntrySet<Entry<K,V>>
// 即: transient Set<Map.Entry<K,V>> entrySet;
//3. 在 entrySet 中,定义类型是 Map.Entry,但是实际上存放的还是 HashMap$Node
// 这是因为 static class Node<K,V> implements Map.Entry<K,V>
//4. 当把 HashMap$Node 对象 存放到 entrySet 就方便我们的遍历,
// 因为 Map.Entry 提供了重要的方法 K getKey(); V getValue();
Set set = map.entrySet();
System.out.println(set.getClass());// class java.util.HashMap$EntrySet
for (Object obj : set){
// System.out.println(obj.getClass());// class java.util.HashMap$Node
//为了从 HashMap$Node 取出k-v
//1、先做一个向下转型
Map.Entry entry = (Map.Entry)obj;
System.out.println(entry.getKey() + "-" + entry.getValue());
}
System.out.println("----------------");
Set set1 = map.keySet();//获取所有key值
System.out.println(set1.getClass());//class java.util.HashMap$KeySet
Collection values = map.values();//获取所有value值
System.out.println(values.getClass());//class java.util.HashMap$Values
}
}
class Car{}
class Person{}
==============控制台输出=================
class java.util.HashMap$EntrySet
no2-李四
no1-张三
com.zzpedu.map_.Car@1b6d3586-com.zzpedu.map_.Person@4554617c
----------------
class java.util.HashMap$KeySet
class java.util.HashMap$Values
debug截图:
Map体系的继承图
Map接口常用方法
1、put
:添加
2、remove
:根据键删除映射关系
3、get
:根据键来获取
4、size
:获取元素的个数
5、isEmpty
:判断个数是否为0
6、clear
:清除
7、containsKey
:查找键是否存在
@SuppressWarnings({"all"})
public class MapMethod {
public static void main(String[] args) {
//演示Map接口常用方法
Map map = new HashMap();
map.put("张三",new Book("",100));
map.put("张三","zs");//替换
map.put("李四","ls");
map.put("老王","lw");
map.put("老刘",null);
map.put(null,"小芳");
map.put("隔壁","老王");
System.out.println("map=" + map);
//remove:根据键删除映射关系
map.remove(null);
System.out.println("map=" + map);
//get:根据键来获取
Object val = map.get("隔壁");
System.out.println("val=" + val);
//size:获取元素的个数
System.out.println("k-v=" + map.size());//5
//isEmpty:判断个数是否为0
System.out.println(map.isEmpty());//false
//clear:清除
map.clear();
System.out.println("map=" + map);//{}
//containsKey:查找键是否存在
System.out.println(map.containsKey("老王"));//false
}
}
class Book{
private String name;
private int num;
public Book(String name, int num) {
this.name = name;
this.num = num;
}
}
==============控制台输出=================
map={null=小芳, 李四=ls, 张三=zs, 老王=lw, 老刘=null, 隔壁=老王}
map={李四=ls, 张三=zs, 老王=lw, 老刘=null, 隔壁=老王}
val=老王
k-v=5
false
map={}
false
Map接口遍历方法
Map遍历的示意图(比List,和Set 复杂点,但是基本原理一样)
1、containsKey
:查找键是否存在
2、keySet
:获取所有的键
3、entrySet
:获取所有的关系
4、values
:获取所有的值
代码演示:
@SuppressWarnings({"all"})
public class MapFor {
public static void main(String[] args) {
Map map = new HashMap();
map.put("张三","zs");
map.put("李四","ls");
map.put("老王","lw");
//第一组:先取所有的Key,通过Key 取出对应的Value
Set keySet = map.keySet();
//(1) 增强for
System.out.println("------------第一种方式 增强for------------");
for (Object key: keySet) {
System.out.println(key + "-" + map.get(key));
}
//(2) 迭代器
System.out.println("------------第二种方式 迭代器------------");
Iterator iterator = keySet.iterator();
while (iterator.hasNext()){
Object key = iterator.next();
System.out.println(key + "-" + map.get(key));
}
//第二组:把所有的values值取出
Collection values = map.values();
//这里可以使用所有的Collections使用的遍历方法
//(1) 增强for
System.out.println("------------取出所有的value 增强for------------");
for (Object value : values) {
System.out.println("value=" + value);
}
//(2) 迭代器
System.out.println("------------取出所有的value 迭代器------------");
Iterator iterator2 = values.iterator();
while (iterator2.hasNext()){
Object value = iterator2.next();
System.out.println("value=" + value);
}
//第三组:通过EntrySet 来获取 k-v
Set entrySet = map.entrySet();//EntrySet<Map.Entry<K,V>>
//(1) 增强for
System.out.println("------------使用EntrySet 增强for(第3种)------------");
for (Object obj : entrySet) {
//将obj 转成 Map.Entry
Map.Entry entry = (Map.Entry) obj;
System.out.println(entry.getKey() + "-" + entry.getValue());
}
//(2) 迭代器
System.out.println("------------使用EntrySet 迭代器(第3种)------------");
Iterator iterator3 = entrySet.iterator();
while (iterator3.hasNext()){
Object next = iterator3.next();
//System.out.println(next.getClass());//HashMap$Node - 实现 -> Map.Entry (getKey,getValue)
//向下转型 HashMap$Node -> Map.Entry
Map.Entry entry = (Map.Entry) next;
System.out.println(entry.getKey() + "-" + entry.getValue());
}
}
}
==============控制台输出=================
------------第一种方式 增强for------------
李四-ls
张三-zs
老王-lw
------------第二种方式 迭代器------------
李四-ls
张三-zs
老王-lw
------------取出所有的value 增强for------------
value=ls
value=zs
value=lw
------------取出所有的value 迭代器------------
value=ls
value=zs
value=lw
------------使用EntrySet 增强for(第3种)------------
李四-ls
张三-zs
老王-lw
------------使用EntrySet 迭代器(第3种)------------
李四-ls
张三-zs
老王-lw
Map接口练习
使用HashMap添加3个员工对象,要求:
键:员工id
值:员工对象
并遍历显示工资 >18000的员工(遍历方式最少两种)
员工类:姓名、工资、员工id
@SuppressWarnings({"all"})
public class MapExercise {
public static void main(String[] args) {
Map hashMap = new HashMap();
//添加对象
hashMap.put(1,new Emp("jack",30000,1));
hashMap.put(2,new Emp("tom",21000,2));
hashMap.put(3,new Emp("milan",12000,3));
System.out.println("hashMap=" + hashMap);
//遍历两种方式
//1 使用keySet -> 增强for
// 并遍历显示工资 >18000的员工(遍历方式最少两种)
System.out.println("-----------第一种遍历方式 增强for-----------");
Set set = hashMap.keySet();
for (Object key : set){
//先获取value
Emp emp = (Emp) hashMap.get(key);
if(emp.getSal() > 18000){
System.out.println(emp);
}
}
//2 使用EntrySet -> 迭代器
// 体现比较难的知识点 包装
Set entrySet = hashMap.entrySet();
Iterator iterator = entrySet.iterator();
System.out.println("-----------第二种遍历方式 迭代器-----------");
while (iterator.hasNext()){
Map.Entry entry = (Map.Entry)iterator.next();
// 通过entry 取出key value
Emp emp = (Emp) entry.getValue();
if(emp.getSal() > 18000){
System.out.println(emp);
}
}
}
}
/**
* 使用HashMap添加3个员工对象,要求:
* 键:员工id
* 值:员工对象
*
* 并遍历显示工资 >18000的员工(遍历方式最少两种)
* 员工类:姓名、工资、员工id
*/
class Emp{
private String name;
private double sal;
private int id;
public Emp(String name, double sal, int id) {
this.name = name;
this.sal = sal;
this.id = id;
}
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public double getSal() { return sal; }
public void setSal(double sal) { this.sal = sal; }
public int getId() { return id; }
public void setId(int id) { this.id = id; }
@Override
public String toString() {
return "Emp{" +
"name='" + name + '\'' +
", sal=" + sal +
", id=" + id +
'}';
}
}
HashMap小结
1、Map
接口的常用实现类:HashMap
、Hashtable
和 Properties
。
2、HashMap
是 Map
接口使用频率最高的实现类
3、HashMap
是以 key-value
对的方式来存储数据
4、key
不能重复,但是是值可以重复,允许使用null键和null值
5、如果添加相同的key
,则会覆盖原来的key-value
,等同于修改。(key 不会替换,value会替换)
6、与HashSet
一样,不保证映射的顺序,因为底层是以`hash表的方式来存储的(JDK8的 HashMap 的数组 + 链表 +红黑树)
7、HashMap
没有实现同步,因此是线程不安全的,方法没有做同步互斥操作,没有 synchronized
关键字修饰
HashMap
HashMap底层机制及源码剖析
示意图:
1)(K,V
)是一个Node
实现了Map.Entry<K,V>
,查看 HashMap
的源码可以看到。
2)JDK7.0 的HashMap
底层实现 [数组+链表],JDK8.0 底层是 [数组+链表+红黑树]
扩容机制 [和HashSet相同]
1)HashMap
底层维护了Node
类型的数组table
,默认为null
2)当创建对象时,将加载因子(loadfactor
)初始化为 0.75
3)当添加key-value
时,通过key
的哈希值
得到在table
表的索引。然后判断该索引处是否有元素,如果没有元素就直接添加。如果该索引处有元素,继续判断该元素的key
和准备加入的key
是否相等,如果相等,则直接替换val
;如果不相等需要判断是树结构还是链表结构,做出相应处理。如果添加是发现容量不够,则需要扩容。
4)第1次添加,则需要扩容table
容量为16,临界值(threshold
)为12(16*0.75)。
5)以后再扩容,则需要扩容table
容量为原来的2
倍(32),临界值为原来的2倍,即24,依次类推
6)在Java8中,如果一条链表的元素超过 TREEIFY_THRESHOLD
(默认是8),并且table
的大小 >=
MIN_TREEIFY_CAPACITY
(默认64),就会进行树化(红黑树)
HashMap源码解读
代码演示:
@SuppressWarnings({"all"})
public class HashMapSource {
public static void main(String[] args) {
HashMap map = new HashMap();
map.put("java",10);
map.put("php",10);
map.put("java",20);//替换value
System.out.println("map="+map);//map={java=20, php=10}
}
}
源码示例:
package java.util;
public class HashMap<K,V> extends AbstractMap<K,V>
implements Map<K,V>, Cloneable, Serializable {
...
transient Node<K,V>[] table;
/**
* The load factor used when none specified in constructor.
*/
static final float DEFAULT_LOAD_FACTOR = 0.75f;
/**
* Constructs an empty <tt>HashMap</tt> with the default initial capacity
* (16) and the default load factor (0.75).
*/
//1 执行构造器 初始化加载因子loadFactor =0.75
// HashMap$Node[] table = null;
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}
//2 执行put方法 会调用hash方法 计算 key的 hash值 (h = key.hashCode()) ^ (h >>> 16)
public V put(K key, V value) {//K = "java" V = 10
return putVal(hash(key), key, value, false, true);
}
// 计数hash值
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
//3 执行putVal 核心方法
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;//辅助变量
//如果底层的table 数组为null 或者 length=0,就扩容到16
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
// 取出hash值对应的table的索引位置的Node,如果为null,就直接把加入的k-v
// ,创建一个Node,加入该位置即可
if ((p = tab[i = (n - 1) & hash]) == null)/
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;//辅助变量
// 如果该table的索引位置的key的hash值和新的key的hash值相同,
// 并且 满足(table现有的节点的key和准备添加的key是同一个对象 或者 equals返回true )
// 就认为不能加新的 k-v
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
// 如果当前的table的已有的Node,是红黑树,就按照红黑树的方式处理
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
// 如果找到的节点,后面是链表,就循环比较
for (int binCount = 0; ; ++binCount) {//死循环
//如果整个链表,没有和他相同(equals),就加到该链表的最后
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
//加入后,判断当前链表的个数,是否已经到8个后
// 就调用 treeifyBin方法进行红黑树的转换
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
//如果在循环比较过程中,发现有相同,就不添加break,后面只是替换value
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
if (e != null) { // existing mapping for key
V oldValue = e.value;//取出原来的value值
if (!onlyIfAbsent || oldValue == null)
// 替换 key 对应的value值,即新的value
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;//每增加一个Node,就size ++
if (++size > threshold[12-24-48])//如果size > 临界值,就扩容
resize();
afterNodeInsertion(evict);
return null;
}
// 5.关于树化(转换红黑树)
//如果 table为null,或者大小 还没到64,就暂时不树化,而是进行扩容
// 否则才会真正的树化 -> 剪枝
final void treeifyBin(Node<K,V>[] tab, int hash) {
int n, index; Node<K,V> e;
if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY(64))
resize();//扩容
else if ((e = tab[index = (n - 1) & hash]) != null) {.....}
}
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
// 扩容resize Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];默认扩容为16
final Node<K,V>[] resize() {
Node<K,V>[] oldTab = table;
int oldCap = (oldTab == null) ? 0 : oldTab.length;
int oldThr = threshold;
int newCap, newThr = 0;
if (oldCap > 0) {
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return oldTab;
}
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
newThr = oldThr << 1; // double threshold
}
else if (oldThr > 0) // initial capacity was placed in threshold
newCap = oldThr;
else { // zero initial threshold signifies using defaults
newCap = DEFAULT_INITIAL_CAPACITY;
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
}
if (newThr == 0) {
float ft = (float)newCap * loadFactor;
newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
(int)ft : Integer.MAX_VALUE);
}
threshold = newThr;
@SuppressWarnings({"rawtypes","unchecked"})
Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];初始化数组容量为16
table = newTab;
....
return newTab;
}
}
HashMap触发扩容、树化情况
代码示例:
@SuppressWarnings({"all"})
public class HashMapSource2 {
public static void main(String[] args) {
HashMap hashMap = new HashMap();
for (int i = 1; i <= 12 ; i++) {
hashMap.put(new A(i),"hello");
}
System.out.println("hashMap=" + hashMap);//12 个 k-v
}
}
class A{
private int num;
public A(int num) {
this.num = num;
}
//所有的A对象的hashCode都是100
@Override
public int hashCode() {
return 100;
}
@Override
public String toString() {
return "\nA{" +
"num=" + num +
'}';
}
}
dubug截图:
当size=2时;在hash值相同的位置形成链表(table容量16)
当size=9时,还是链表(这时不会转换成红黑树,而是扩容table为32)
当size=10时,还是链表(这时不会转换成红黑树,而是扩容table为64)
当size=11时,这是的链表转成红黑树 HashMao$TreeNode(满足链表 >= 8,table容量 >= 64)
如果数组的链表没有超过8个,数组会一直的扩容
16(12) --> 32(24) --> 64(48) --> 128(96) --> 256(192) …
TreeMap
代码演示:
@SuppressWarnings({"all"})
public class TreeMapDemo {
public static void main(String[] args) {
//使用默认的构造器,创建TreeMap, 是无序的(也没有排序)
/*
要求:按照传入的key大小进行排序
*/
// TreeMap treeMap = new TreeMap();
TreeMap treeMap = new TreeMap(new Comparator() {
@Override
public int compare(Object o1, Object o2) {
//按照传入的key(String)的大小排序
// return ((String) o1).compareTo((String) o2);
//按照传入的key(String)的长度大小排序
return ((String) o1).length() - ((String) o2).length();
}
});
treeMap.put("jack","杰克");
treeMap.put("tom","汤姆");
treeMap.put("kristina","克瑞斯提诺");
treeMap.put("smith","史密斯");
treeMap.put("zzp","zzp");//加入不了 因为new对象的时候指定了按照key的长度大小排序 但是会替换value的值
//System.out.println("treeMap=" + treeMap);//无序 treeMap={jack=杰克, kristina=克瑞斯提诺, smith=史密斯, tom=汤姆}
//System.out.println("treeMap=" + treeMap);//有序 treeMap={jack=杰克, kristina=克瑞斯提诺, smith=史密斯, tom=汤姆}
System.out.println("treeMap=" + treeMap);// treeMap={tom=zzp, jack=杰克, smith=史密斯, kristina=克瑞斯提诺}
/*
解读源码:
1. 构造器,把传入的实现了 Comparator接口的匿名内部类(对象)传给了TreeMap的comparator
public TreeMap(Comparator<? super K> comparator) {
this.comparator = comparator;
}
2.调用put方法
2.1 第一次添加,把k-v封装到 Entry对象中,放入到root
Entry<K,V> t = root;
if (t == null) {
compare(key, key); // type (and possibly null) check
root = new Entry<>(key, value, null);
size = 1;
modCount++;
return null;
}
2.2 以后添加
Comparator<? super K> cpr = comparator;
if (cpr != null) {
do {//遍历所有的key,给当前的key找到适当的位置
parent = t;
cmp = cpr.compare(key, t.key);//动态绑定到我们的匿名内部类的compare方法
if (cmp < 0)
t = t.left;
else if (cmp > 0)
t = t.right;
else //如果在遍历过程中,发现准备添加Key和当前已有的Key 是相等,就不添加
return t.setValue(value);
} while (t != null);
}
*/
}
}
TreeMap源码示例:
package java.util;
public class TreeMap<K,V>
extends AbstractMap<K,V>
implements NavigableMap<K,V>, Cloneable, java.io.Serializable
{
...
private final Comparator<? super K> comparator;
//1.构造器,把传入的实现了 Comparator接口的匿名内部类(对象)传给了TreeMap的comparator
public TreeMap(Comparator<? super K> comparator) {
this.comparator = comparator;
}
//2.调用put方法
public V put(K key, V value) {
Entry<K,V> t = root;
// 第一次进来,t == null,把k-v封装到 Entry对象中,放入到root
if (t == null) {
compare(key, key); // type (and possibly null) check
root = new Entry<>(key, value, null);
size = 1;
modCount++;
return null;
}
int cmp;
Entry<K,V> parent;
// split comparator and comparable paths
// 以后添加
Comparator<? super K> cpr = comparator;
if (cpr != null) {
do { //遍历所有的key,给当前的key找到适当的位置
parent = t;
cmp = cpr.compare(key, t.key);//动态绑定到我们的匿名内部类的compare方法
if (cmp < 0)
t = t.left;
else if (cmp > 0)
t = t.right;
else //如果在遍历过程中,发现准备添加key和当前已有的key 是相等,就不添加
return t.setValue(value);
} while (t != null);
}
else {
if (key == null)
throw new NullPointerException();
@SuppressWarnings("unchecked")
Comparable<? super K> k = (Comparable<? super K>) key;
do {
parent = t;
cmp = k.compareTo(t.key);
if (cmp < 0)
t = t.left;
else if (cmp > 0)
t = t.right;
else
return t.setValue(value);
} while (t != null);
}
Entry<K,V> e = new Entry<>(key, value, parent);
if (cmp < 0)
parent.left = e;
else
parent.right = e;
fixAfterInsertion(e);
size++;
modCount++;
return null;
}
}
Hashtable
HashTable的基本介绍
1)存放的元素是键值对:即k-v
2)hashtable
的键和值都不能为null
,否则会抛出NullPointerException
3)hashtable
使用方法基本上和 HashMap
一样
4)hashtable
是线程安全的(synchronized
),hashMap
是线程不安全的
Hashtable源码底层加了 synchronized 修饰
package java.util;
public class Hashtable<K,V>
extends Dictionary<K,V>
implements Map<K,V>, Cloneable, java.io.Serializable {
...
public synchronized V put(K key, V value) {...}
}
HashTable的应用案例
@SuppressWarnings({"all"})
public class HashTableExercise {
public static void main(String[] args) {
Hashtable table = new Hashtable();//ok
table.put("john",100);//ok
//table.put(null,100);//异常 NullPointerException
//table.put("john",null);//异常 NullPointerException
table.put("lucy",100);//ok
table.put("lic",100);//ok
table.put("lic",80);//替换
System.out.println("table=" + table);//table={john=100, lic=80, lucy=100}
//简单说明一下Hashtable的底层
//1. 底层有数组 Hashtable$Entry[] 初始化大小为 11
//2. threshold(临界值) 8 = 11*0.75
//3. 扩容:按照自己的扩容机制来进行即可。
//4. 执行方法 addEntry(hash, key, value, index); 添加K-V 封装到Entry
//5. 当 if (count >= threshold) 满足时,就进行扩容
//6. 按照 int newCapacity = (oldCapacity << 1) + 1; 的大小扩容(2倍+1)
}
}
源码:
package java.util;
public class Hashtable<K,V>
extends Dictionary<K,V>
implements Map<K,V>, Cloneable, java.io.Serializable {
// 底层是数组 Hashtabe$Entry
private transient Entry<?,?>[] table;
private int threshold;
// 1 初始化容量大小为11 负载因子0.75
public Hashtable() {
this(11, 0.75f);
}
// 2 threshold 临界值 8 = 11 * 0.75
public Hashtable(int initialCapacity, float loadFactor) {
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
if (loadFactor <= 0 || Float.isNaN(loadFactor))
throw new IllegalArgumentException("Illegal Load: "+loadFactor);
if (initialCapacity==0)
initialCapacity = 1;
this.loadFactor = loadFactor;
table = new Entry<?,?>[initialCapacity];
threshold = (int)Math.min(initialCapacity * loadFactor, MAX_ARRAY_SIZE + 1);
}
//添加元素put
public synchronized V put(K key, V value) {
// Make sure the value is not null
if (value == null) {
//**这里Hashtable的value值 不能为null的原因**
throw new NullPointerException();
}
// Makes sure the key is not already in the hashtable.
Entry<?,?> tab[] = table;
int hash = key.hashCode();//获取hash值
int index = (hash & 0x7FFFFFFF) % tab.length;//计算索引
@SuppressWarnings("unchecked")
Entry<K,V> entry = (Entry<K,V>)tab[index];
for(; entry != null ; entry = entry.next) {
if ((entry.hash == hash) && entry.key.equals(key)) {//判断key的hash值与新的key的hash值是否相同,如果相同替换value值
V old = entry.value;
entry.value = value;//替换
return old;
}
}
//真正执行添加元素操作
addEntry(hash, key, value, index);
return null;
}
// 真正执行添加put(k,v)操作 封装到Entry
private void addEntry(int hash, K key, V value, int index) {
modCount++;
Entry<?,?> tab[] = table;
if (count >= threshold) {//判断是否大于临界值
// Rehash the table if the threshold is exceeded
rehash();//扩容
tab = table;
hash = key.hashCode();
index = (hash & 0x7FFFFFFF) % tab.length;
}
// Creates the new entry.
@SuppressWarnings("unchecked")
Entry<K,V> e = (Entry<K,V>) tab[index];
tab[index] = new Entry<>(hash, key, value, e);
count++;
}
// Hashtable底层的扩容
protected void rehash() {
int oldCapacity = table.length;//11
Entry<?,?>[] oldMap = table;
// overflow-conscious code
// oldCapacity << 1 oldCapacity 乘以2 + 1 = 23
int newCapacity = (oldCapacity << 1) + 1;
if (newCapacity - MAX_ARRAY_SIZE > 0) {
if (oldCapacity == MAX_ARRAY_SIZE)
// Keep running with MAX_ARRAY_SIZE buckets
return;
newCapacity = MAX_ARRAY_SIZE;
}
//创建新的数组 扩容
Entry<?,?>[] newMap = new Entry<?,?>[newCapacity];
modCount++;
threshold = (int)Math.min(newCapacity * loadFactor, MAX_ARRAY_SIZE + 1);
table = newMap;
for (int i = oldCapacity ; i-- > 0 ;) {
//把旧的数组节点从新hash值放入新的数组中
for (Entry<K,V> old = (Entry<K,V>)oldMap[i] ; old != null ; ) {
Entry<K,V> e = old;
old = old.next;
int index = (e.hash & 0x7FFFFFFF) % newCapacity;
e.next = (Entry<K,V>)newMap[index];
newMap[index] = e;
}
}
}
//静态内部类Entry
private static class Entry<K,V> implements Map.Entry<K,V> {
...
}
}
Hashtable 和 HashMap 相比
版本 | 线程安全(同步) | 效率 | 允许null键null值 | |
---|---|---|---|---|
HashMap | 1.2 | 不安全 | 高 | 允许 |
Hashtable | 1.0 | 安全 | 较低 | 不允许 |
Properties
基本介绍
1、Properties
类继承自 Hashtable
类并且实现了 Map
接口,也是接口使用一种键值对的形式来保存数据。
package java.util;
public
class Properties extends Hashtable<Object,Object> {}
2、它的使用特点和 Hashtable
类似
3、Properties
还可以用于 xxx.properties
文件中,加载数据到Properties 类对象,并进行读取和修改
4、说明:工作后 xxx.properties
文件通常作为配置文件,这个知识点在IO流举例。
基本使用
@SuppressWarnings({"all"})
public class PropertiesDemo {
public static void main(String[] args) {
//解读:
//1. Properties 继承 Hashtable
//2. 可以通过 k-v 存放数据,当然 key 和 value 不能为 null
Properties properties = new Properties();
properties.put("john",100);// k-v
//properties.put(null,100);//抛出异常 NullPointerException
//properties.put("john",null);//抛出异常 NullPointerException
properties.put("lucy",100);
properties.put("john",80);//如果有相同的key,value被替换
System.out.println("properties=" + properties);//{john=80, lucy=100}
// 通过key,获取对应值
System.out.println(properties.get("lucy"));//100
// 删除元素
properties.remove("lucy");
System.out.println("properties=" + properties);//{john=80}
// 修改
properties.put("john","约翰");
System.out.println("properties=" + properties);//{john=约翰}
}
}
小总结
总结-开发中如何选择集合实现类
在开发中,选择什么集合实现类,主要取决于业务操作特点,然后根据集合实现类特性进行选择,分析如下:
1)先判断存储的类型(一组对象[单例]或一组键值对[双列])
2)一组对象[单例]:Collection接口
允许重复:List
增删多:LinkedList [底层维护了一个双向链表]
改查多:ArrayList [底层维护 Object类型的可变数组]
不允许重复:Set
无序:HashSet [底层是HashMap,维护了一个哈希表,即(数组+链表+红黑树)]
排序: TreeSet
插入和取出顺序一致:LinkedHashSet[底层LinkedHashMap的底层HashMap],维护数组+双向链表
3)一组键值对[双列]:Map
键无序:HashMap [底层是:哈希表 jdk7:数组+链表,jdk8:数组+链表+红黑树]
键排序:TreeMap
键插入和取出顺序一致:LinkedHashMap
读取文件:Properties
七、Collections
Collections工具类介绍
1)Collections
是一个操作 Set
、List
和 Map
等集合的工具类
2)Collections
中提供了一系列静态方法对集合进行排序、查询和修改等操作
排序操作(均为static方法)
1)reverse(List)
:反转 List
中元素的顺序
2)shuffle(List)
:对 List
集合元素进行随机排序
3)sort(List)
:根据元素的自然数顺序对指定 List
集合元素按升序排序
4)sort(List, Comparator)
:根据指定的 Comparator
产生的顺序对 List
集合进行排序
5)swap(List, int, int)
:将指定 list
集合中的 i 处和 j 处元素进行交换
@SuppressWarnings({"all"})
public class Collections_ {
public static void main(String[] args) {
//创建ArrayList集合,用于测试
List list = new ArrayList();
list.add("tom");
list.add("smith");
list.add("king");
list.add("milan");
//reverse(List):反转 List 中元素的顺序
Collections.reverse(list);
System.out.println("list=" + list);
//shuffle(List):对 List 集合元素进行随机排序
// for (int i = 0; i < 5; i++) {
// Collections.shuffle(list);
// System.out.println("list=" + list);
// }
//sort(List):根据元素的自然数顺序对指定 List 集合元素按升序排序
Collections.sort(list);
System.out.println("自然数顺序后=" + list);
//sort(List, Comparator):根据指定的 Comparator 产生的顺序对 List 集合进行排序
// 按照字符串长度大小排序
Collections.sort(list, new Comparator() {
@Override
public int compare(Object o1, Object o2) {
// if(o1 instanceof String){} 严谨可以加判断
return ((String) o1).length() - ((String) o2).length() ;
}
});
System.out.println("字符串长度大小排序=" + list);
//swap(List, int, int):将指定 list 集合中的 i 处和 j 处元素进行交换
Collections.swap(list,0,1);
System.out.println("交换后的情况=" + list);
}
}
==============控制台输出=================
list=[milan, king, smith, tom]
自然数顺序后=[king, milan, smith, tom]
字符串长度大小排序=[tom, king, milan, smith]
交换后的情况=[king, tom, milan, smith]
查找、替换
1)Object max(Collection)
:根据元素的自然顺序,返回给定集合中的最大元素
2)Object max(Collection, Comparator)
:根据 Comparator
指定的顺序,返回给定集合中最大元素
3)Object min(Collection)
:根据元素的自然顺序,返回给定集合中的最小元素
4)Object min(Collection, Comparator)
:根据 Comparator
指定的顺序,返回给定集合中最小元素
5)int frequency(Collection, Object)
:返回指定集合中指定元素的出现次数
6)void copy(List dest, List src)
:将 src
中的内容复制到dest
中
7)Boolean replaceAll(List list, Object oldVal, Object newVal)
:使用新值替换 List
对象的所有旧值
代码演示:
@SuppressWarnings({"all"})
public class CollectionsDemo {
public static void main(String[] args) {
//创建ArrayList集合,用于测试
List list = new ArrayList();
list.add("tom");
list.add("smith");
list.add("king");
list.add("milan");
//Object max(Collection):根据元素的自然顺序,返回给定集合中的最大元素
System.out.println("自然顺序最大元素=" + Collections.max(list));
//Object max(Collection, Comparator):根据 Comparator 指定的顺序,返回给定集合中最大元素
//比如,返回长度最大的元素
Object maxObject = Collections.max(list, new Comparator() {
@Override
public int compare(Object o1, Object o2) {
return ((String) o1).length() - ((String) o2).length();
}
});
System.out.println("长度最大的元素=" + maxObject);
//Object min(Collection):根据元素的自然顺序,返回给定集合中的最小元素
System.out.println("自然顺序的最小元素=" + Collections.min(list));//king
//Object min(Collection, Comparator):根据 Comparator 指定的顺序,返回给定集合中最小元素
Object minObject = Collections.min(list, new Comparator() {
@Override
public int compare(Object o1, Object o2) {
return ((String) o1).length() - ((String) o2).length();
}
});
System.out.println("指定(长度)的顺序的最小元素=" + minObject);
//int frequency(Collection, Object):返回指定集合中指定元素的出现次数
list.add("tom");
System.out.println("tom出现的次数=" + Collections.frequency(list,"tom"));
//void copy(List dest, List src):将 src 中的内容复制到dest中
// 注意 dest必须大于或等于src的长度 否则抛出异常 IndexOutOfBoundsException
ArrayList dest = new ArrayList();
//为了完成一个完整的拷贝,我们需要先给dest 赋值,大小和 list.size() 一样
for (int i = 0; i < list.size(); i++) {
dest.add("");
}
//拷贝
Collections.copy(dest,list);
System.out.println("拷贝后的dest=" + dest);
//Boolean replaceAll(List list, Object oldVal, Object newVal):使用新值替换 List 对象的所有旧值
//如果list中,有 tom 就替换成 汤姆
Collections.replaceAll(list,"tom","汤姆");
System.out.println("list替换后=" + list);
}
}
==============控制台输出=================
自然顺序最大元素=tom
长度最大的元素=smith
自然顺序的最小元素=king
指定(长度)的顺序的最小元素=tom
tom出现的次数=2
拷贝后的dest=[tom, smith, king, milan, tom]
list替换后=[汤姆, smith, king, milan, 汤姆]
作业
1、编程一:
按要求实现:
(1)封装一个新闻类,包含标题和内容属性,提供get、set方法,重写toString方法,打印对象时只打印标题:
(2)只提供一个带参数的构造器,实例化对象时,只初始化标题:并且实例化两个对象:
新闻一:新冠确诊病例超千万,数百万印度教徒赴恒河“圣浴”引起民众担忧
新闻二:男子突然想起2个月前钓的鱼还在网兜里,捞起来一看赶紧放生
(3)将新闻对象添加到ArrayList 集合中,并且进行倒序遍历
(4)在遍历集合过程中,对新闻标题进行处理,超过15字的只保留前15个,然后在后面加 “…”
(5)在控制台打印遍历出经过处理的新闻标题:
@SuppressWarnings({"all"})
public class Homework01 {
public static void main(String[] args) {
ArrayList arrayList = new ArrayList();
arrayList.add(new News("新冠确诊病例超千万,数百万印度教徒赴恒河 \"圣浴\" 引起民众担忧"));
arrayList.add(new News("男子突然想起2个月前钓的鱼还在网兜里,捞起来一看赶紧放生"));
int size = arrayList.size();
for (int i = size - 1; i >= 0; i--) {
// System.out.println(arrayList.get(i));
News news = (News)arrayList.get(i);
System.out.println(processTitle(news.getTitle()));
}
//Collections.reverse(arrayList); //反转 List 中元素的顺序
}
//专门写一个方法,处理实现新闻标题 process处理
public static String processTitle(String title){
if(title == null){
return "";
}
if(title.length() > 15){
return title.substring(0,15) + "...";//[0,15)
}else {
return title;
}
}
}
/**
* (1)封装一个新闻类,包含标题和内容属性,提供get、set方法,重写toString方法,打印对象时只打印标题:
* <p>
* (2)只提供一个带参数的构造器,实例化对象时,只初始化标题:并且实例化两个对象:
* 新闻一:新冠确诊病例超千万,数百万印度教徒赴恒河“圣浴”引起民众担忧
* 新闻二:男子突然想起2个月前钓的鱼还在网兜里,捞起来一看赶紧放生
* <p>
* (3)将新闻对象添加到ArrayList 集合中,并且进行倒序遍历
* <p>
* (4)在遍历集合过程中,对新闻标题进行处理,超过15字的只保留前15个,然后在后面加 “…”
* <p>
* (5)在控制台打印遍历出经过处理的新闻标题:
*/
class News {
private String title;
private String content;
public News(String title) { this.title = title; }
public String getTitle() { return title; }
public void setTitle(String title) { this.title = title; }
public String getContent() { return content; }
public void setContent(String content) { this.content = content; }
@Override
public String toString() {
return "News{" +
"title='" + title + '\'' +
'}';
}
}
==============控制台输出=================
男子突然想起2个月前钓的鱼还在...
新冠确诊病例超千万,数百万印度...
2、编程二:
使用ArrayList 完成对 对象 Car{name,price}的各种操作
1、add:添加元素
2、remove:删除指定元素
3、contains:查找元素是否存在
4、size:获取元素个数
5、isEmpty:判断是否为空
6、clear:清空
7、addAll:添加多个元素
8、containsAll:查找多个元素是否都存在
9、removeAll:删除多个元素
使用增强for循环 和 迭代器来遍历所有的car,需要重写 Car 的toString方法
@SuppressWarnings({"all"})
public class Homework02 {
public static void main(String[] args) {
ArrayList arrayList = new ArrayList();
Car car1 = new Car("宝马",40000);
Car car2 = new Car("宾利",500000);
//1、add:添加元素
arrayList.add(car1);
arrayList.add(car2);
System.out.println("arrayList=" + arrayList);
//2、remove:删除指定元素
arrayList.remove(car1);
System.out.println("arrayList=" + arrayList);
//3、contains:查找元素是否存在
System.out.println(arrayList.contains(car1));
//4、size:获取元素个数
System.out.println(arrayList.size());
//5、isEmpty:判断是否为空
System.out.println(arrayList.isEmpty());
//6、clear:清空
//arrayList.clear();
//7、addAll:添加多个元素
System.out.println("arrayList=" + arrayList);
arrayList.addAll(arrayList);
System.out.println("arrayList=" + arrayList);
//8、containsAll:查找多个元素是否都存在
System.out.println(arrayList.containsAll(arrayList));
//9、removeAll:删除多个元素
//arrayList.removeAll(arrayList);//相当于清空
//使用增强for循环 和 迭代器来遍历所有的car,需要重写 Car 的toString方法
System.out.println("------------增强for来遍历------------");
for (Object obj : arrayList){
System.out.println((Car)obj);
}
System.out.println("------------迭代器来遍历------------");
Iterator iterator = arrayList.iterator();
while (iterator.hasNext()){
Object next = iterator.next();
System.out.println(next);
}
}
}
/**
* 使用ArrayList 完成对 对象 Car{name,price}的各种操作
* 1、add:添加元素
* 2、remove:删除指定元素
* 3、contains:查找元素是否存在
* 4、size:获取元素个数
* 5、isEmpty:判断是否为空
* 6、clear:清空
* 7、addAll:添加多个元素
* 8、containsAll:查找多个元素是否都存在
* 9、removeAll:删除多个元素
* 使用增强for循环 和 迭代器来遍历所有的car,需要重写 Car 的toString方法
*/
class Car{
private String name;
private double price;
public Car(String name, double price) {
this.name = name;
this.price = price;
}
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public double getPrice() { return price; }
public void setPrice(double price) { this.price = price; }
@Override
public String toString() {
return "Car{" +
"name='" + name + '\'' +
", price=" + price +
'}';
}
}
==============控制台输出=================
arrayList=[Car{name='宝马', price=40000.0}, Car{name='宾利', price=500000.0}]
arrayList=[Car{name='宾利', price=500000.0}]
false
1
false
arrayList=[Car{name='宾利', price=500000.0}]
arrayList=[Car{name='宾利', price=500000.0}, Car{name='宾利', price=500000.0}]
true
------------增强for来遍历------------
Car{name='宾利', price=500000.0}
Car{name='宾利', price=500000.0}
------------迭代器来遍历------------
Car{name='宾利', price=500000.0}
Car{name='宾利', price=500000.0}
3、编程三:
按照要求完成下来任务:
1)使用HashMap类实例化一个Map类型的对象m,键(String)和值(int)分别用于存储员工的姓名和工资,存入数据:jack-650元;tom-1200元;smith-2900元;
2)将jack的工资改为2600元
3)为所有员工工资加薪100元
4)遍历集合中所有的员工
5)遍历集合中所有的工资
@SuppressWarnings({"all"})
public class Homework03 {
public static void main(String[] args) {
Map map = new HashMap();
map.put("jack",650);//int -> Integer 自动装箱
map.put("tom",1200);//int -> Integer
map.put("smith",2900);//int -> Integer
System.out.println("map=" + map);
map.put("jack",2600);//替换 更新
System.out.println("map=" + map);
//为所有员工工资加薪100元
Set keySet = map.keySet();
for(Object key : keySet){
//更新
map.put(key,(Integer)map.get(key) + 100);
}
System.out.println("更新后map=" + map);
//遍历 Entry
Set entrySet = map.entrySet();
System.out.println("------------遍历------------");
//迭代器
Iterator iterator = entrySet.iterator();
while (iterator.hasNext()) {
Map.Entry entry = (Map.Entry)iterator.next();
System.out.println(entry.getKey() + "-" + entry.getValue());
}
//遍历集合中所有的工资
System.out.println("------------遍历集合中所有的工资------------");
Collection values = map.values();
for (Object obj : values){
System.out.println("工资=" + obj);
}
}
}
/**
* 按照要求完成下来任务:
* 1)使用HashMap类实例化一个Map类型的对象m,键(String)和值(int)分别用于存储员工的姓名和工资,存入数据:
* jack-650元;tom-1200元;smith-2900元;
* 2)将jack的工资改为2600元
* 3)为所有员工工资加薪100元
* 4)遍历集合中所有的员工
* 5)遍历集合中所有的工资
*/
==============控制台输出=================
map={tom=1200, smith=2900, jack=650}
map={tom=1200, smith=2900, jack=2600}
更新后map={tom=1300, smith=3000, jack=2700}
------------遍历------------
tom-1300
smith-3000
jack-2700
------------遍历集合中所有的工资------------
工资=1300
工资=3000
工资=2700
4、简答题:
试分析HashSet和TreeSet分别如何实现去重的
(1)HashSet的去重机制:hashCode() + equals()
,底层通过存入对象,进行运算得到一个hash
值,通过hash
值得到对应的索引,如果发现table
索引所在的位置,没有数据,就直接存放。如果有数据,就进行equals
比较[遍历比较],如果比较后,不相同就加入,否则就不加入。
(2)TtrrSet的去重机制:如果你传入了一个Comparator
匿名对象,就使用实现的compare
方法去重,如果方法返回0,就认为是相同的元素/数据,就不添加。如果你没有传入一个Comparator
匿名对象,则以你添加的对象实现的Compareable
接口的compareTo
方法去重。
5、代码分析
下面代码运行会不会抛出异常,并从源码层面说明原因。[ 考察:读源码+接口编程+动态绑定]
TreeSet treeSet = new TreeSet ();
treeSet.add(new Person());
class Person{
}
add 方法:因为 TreeSet ()
构造器没有传入Compatator
接口匿名内部类
所以在底层 Comparable<? super K> k = (Comparable<? super K>) key;
即 把Person
转成 Comparable类型
会抛出异常 treeSet.add(new Person());//ClassCastException.
解决:在Person
类实现Comparable
接口
6、下面代码输出什么?
已知:Person 类按照id和name重写了hashCode和equals方法,问下面代码输出什么?
public static void main(String[] args) {
HashSet set = new HashSet();
Person p1 = new Person(1001,"AA");
Person p2 = new Person(1002,"BB");
set.add(p1);
set.add(p2);
p1.name = "CC";
set.remove(p1);//重新定位hash值 不是原来的hash值了 因为前面 p1.name = "CC";
System.out.println("set=" + set);
set.add(new Person(1001,"CC"));
System.out.println("set=" + set);
set.add(new Person(1001,"AA"));
System.out.println("set=" + set);
}
代码演示:
@SuppressWarnings({"all"})
public class Homework06 {
public static void main(String[] args) {
HashSet set = new HashSet();
Person p1 = new Person(1001,"AA");
Person p2 = new Person(1002,"BB");
set.add(p1);
set.add(p2);
p1.name = "CC";
set.remove(p1);//重新定位hash值 不是原来的hash值了 因为前面 p1.name = "CC";
System.out.println("set=" + set);
set.add(new Person(1001,"CC"));
System.out.println("set=" + set);
set.add(new Person(1001,"AA"));
System.out.println("set=" + set);
}
}
class Person{
public String name;
public int id;
public Person(int id,String name) {
this.name = name;
this.id = id;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Person person = (Person) o;
return id == person.id && Objects.equals(name, person.name);
}
@Override
public int hashCode() {
return Objects.hash(name, id);
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", id=" + id +
'}';
}
}
==============控制台输出=================
set=[Person{name='BB', id=1002}, Person{name='CC', id=1001}]
set=[Person{name='BB', id=1002}, Person{name='CC', id=1001}, Person{name='CC', id=1001}]
set=[Person{name='BB', id=1002}, Person{name='CC', id=1001}, Person{name='CC', id=1001}, Person{name='AA', id=1001}]
7、试写出Vector和ArrayList的比较
底层结构 | 版本 | 线程安全(同步)效率 | 扩容倍数 | |
---|---|---|---|---|
ArrayList | 可变数组 | jdk1.2 | 不安全,效率高 | 如果使用有参构造器,按照1.5倍扩容,如果是无参构造器: 1.第一次扩容10 2.从第二次开始按照1.5倍 |
Vector | 可变数组 Object[] | jdk1.0 | 安全,效率不高 | 如果是无参构造器,默认10,满后,按照2倍扩容 如果指定大小创建(有参)Vector,则每次按照2倍扩容 |