Java基础篇下

304 阅读22分钟

开篇先放下个人的Github地址:masuo777.github.io/ 欢迎访问!!!

Object

作为用的最少(本人之前是不怎么使用Object类的)却又儿孙满堂的Object类,可以说是既遥远却又近在眼前的了,说他遥远是因为目前我们很少会用到他,说他近是因为我们无时不刻在使用他的子类。

他作为最大的父类一共提供了十一个方法。

//
public final native Class<?> getClass();

public native int hashCode();

public boolean equals(Object obj) {
    return (this == obj);
}

protected native Object clone() throws CloneNotSupportedException;

public String toString() {
    return getClass().getName() + "@" + Integer.toHexString(hashCode());
}

public final native void notify();

public final native void notifyAll();

public final native void wait(long timeout) throws InterruptedException;

public final void wait(long timeout, int nanos) throws InterruptedException {
    if (timeout < 0) {
        throw new IllegalArgumentException("timeout value is negative");
    }

    if (nanos < 0 || nanos > 999999) {
        throw new IllegalArgumentException(
            "nanosecond timeout value out of range");
    }

    if (nanos > 0) {
        timeout++;
    }

    wait(timeout);
}

public final void wait() throws InterruptedException {
    wait(0);
}

protected void finalize() throws Throwable { }

equals

  • 基础类型:只能用==来判断相等,判断的是值相等

  • 引用类型:使用equals判断他们是否等价,使用==判断的是他们两个是否引用同一个对象。

    实现:
    • 首先判断是否引用同一个对象
    • 其次判断是否同一个类型

Object的equals()实现

public boolean equals(Object obj) {
    //==:双等号在Java中判断的是两个值是否引用同一个对象
    //判断两个对象是否引用同一个对象
    return (this == obj);
}

String的equals()实现

public boolean equals(Object anObject) {
    //与Object相同
    if (this == anObject) {
        return true;
    }
    //不同的话,判断该对象是否是String类型,在这里有关instanceof的知识可以往上面找
    if (anObject instanceof String) {
        //在这里对对象进行强转,
        String anotherString = (String)anObject;
        //获取自身的长度,这个value是String中早就声明好的final对象,
        //private final char value[];,注意Java8中String还在使用char数组存储字符串,之后则使用byte数组
        int n = value.length;
        //获取传进来的object对象的长度,并比较他们是否长度相等
        if (n == anotherString.value.length) {
            //将自己的数组赋值给v1
            char v1[] = value;
            //获取传进来的object对象的数组,这里上面再进行强转的时候object对象已经有了数组
            char v2[] = anotherString.value;
            int i = 0;
            //长度不为0的时候,持续循环
            while (n-- != 0) {
                //值不相等,则返回false,相等则i++,循环
                if (v1[i] != v2[i])
                    return false;
                i++;
            }
            return true;
        }
    }
    return false;
}

hashcode

这个大家一定都很熟了吧,hashcode,哈希值,又称散列值,所以object的hashcode()方法就是返回对象的哈希值,相等的两个对象哈希值一定相等,但是不相等的两个值散列值,不一定不相等。因为散列值具有随机性,两个值不相等的对象可能算出相同的hash值。

在equals方法覆盖到的地方,同时可以覆盖hashcode方法,保证等价的两个对象具有相同的hash值。

HashSet()方法和HashMap()方法使用了hashcode方法计算对象的存储位置。因此添加到其中的类都实现了hashcode()方法。如果自定义类没有实现hashcode方法,那么他们看起来一样但是不能保证散列值相同,也不能确定他们是相等的。

private static void hashcodeTest() {
    //等价性
    System.out.println("hashcode");
    String s1 = "12333999";
    String s2 = "123";
    System.out.println(s1.equals(s2));//true
    System.out.println(s1.hashCode());//48690
    System.out.println(s2.hashCode());//48690


    char []val = {'1','2','3','4','5','6','7','9','9','9','9'};
    int h = 0;
    //int最大值是2的31次方-1,这里int类型是32位,一位符号位标识正负,初始化为0,表示正数,
    // 当数值大于2的31次方-1时会产生进位操作,导致数值变负数,
    // 2的31次方-1 = 2147483647
    for (int i = 0; i < val.length; i++) {
        System.out.println(Integer.valueOf(val[i]));
        h = 31 * h + val[i];
        System.out.println(h);
    }

}

在上面我对hashcode的源码产生了一个疑惑,现在来对hashcode的源码进行解析一下。

源码:

public int hashCode() {
    int h = hash;//0
    //private int hash; 官方的解释: Default to 0,默认值为0
    
    //h为0保证了只会进入一次,也就是说,hashcode获取一次后就不再改变了
    if (h == 0 && value.length > 0) {
        //将value数组clone给val
        char val[] = value;
		//当i小于数组长度时,持续循环
        for (int i = 0; i < value.length; i++) {
            //计算h得值
            h = 31 * h + val[i];
        }
        //赋值给hash,以后直接通过hash获取
        hash = h;
    }
    //返回hash值
    return h;
}

源码很简单,但是其中存在一个坑,也是我的疑惑,那就是当我的数组足够长时,h的值很快就会超过int类型的上限值(2147483647),此时循环仍在继续,int就会突破上限,临时提升为long类型,之后再取范围内的int值并返回,之间的具体过程可以参考:blog.csdn.net/u011123972/… 。非常感谢这位大佬的解疑。

==在这里R取31是有原因的,31是一个奇素数,奇数能保证信息不会丢失,如果是偶数的话,信息就会丢失。因为与2相乘相当于向左位移一位,最左边的位丢失。==

toString

在一些自定义的类中,在那些toString还没被重写的类中,会输出包名+类名+@+十六进制字符串的形式

private static void toStringTest() {

    ToString ts = new ToString();
    System.out.println(ts.toString());//JavaBase.ToString@1b6d3586

}

String类的toString方法

String s = "123";
s.toString();

 public String toString() {
     return this;
 }

Integer类的toString方法

Integer i = 1;
i.toString();

public String toString() {
    return toString(value);
}

clone

简介

clone()是Object的protected方法,不是public,一个类不显式地去写clone方法,其他类就不能直接去调用该类的clone方法。

private static void cloneTest() {
    class CloneTest1{
        @Override
        protected Object clone() throws CloneNotSupportedException {
            return super.clone();
        }
    }

    class CloneTest2{
        //无clone方法
    }
    
    CloneTest1 ct1 = new CloneTest1();
    CloneTest2 ct2 = new CloneTest2();

    try {
        ct1.clone();//java.lang.CloneNotSupportedException: JavaBase.SeeObject$1CloneTest1
        //在这里看似CloneTest1类可以调用clone方法,但是实际上还是会抛出不支持克隆的异常
    } catch (CloneNotSupportedException e) {
        e.printStackTrace();
    }
    //ct2.clone();//'clone()' has protected access in 'java.lang.Object'
}

我们看一下Object的clone方法源码

protected native Object clone() throws CloneNotSupportedException;

可以看到,因为native的原因这里并没有代码体,因为这不是Java的原生代码,而是外接代码实现,但是可以抛出异常,当我们实现cloneable的接口后,就不会报错了。

class CloneTest1 implements Cloneable{//实现接口
    @Override
    protected Object clone() throws CloneNotSupportedException {
        return (CloneTest1)super.clone();
    }
}

浅拷贝

拷贝对象和原始对象的引用类型引用同一个对象。

private static void skinCloneTest() {
    System.out.println("浅拷贝");
    class SkinClone implements Cloneable{

        private int i ;//default 0
        //首先,声明clone方法
        @Override
        protected SkinClone clone() throws CloneNotSupportedException {
            return (SkinClone)super.clone();
        }

        //构造方法
        public SkinClone(){
            i = 10;
        }

        public int getI() {
            return i;
        }

        public void setI(int i) {
            this.i = i;
        }

    }


    SkinClone sct1 = new SkinClone();
    sct1.setI(50);
    try {
        SkinClone sct2 = sct1.clone();
        System.out.println(sct2.getI());
    } catch (CloneNotSupportedException e) {
        e.printStackTrace();
    }
}

深拷贝

拷贝对象和原始对象的引用类型引用不同对象。

private static void BoneCloneTest() {

    System.out.println("深拷贝");

    class BoneClone implements Cloneable{

        private String s ;

        @Override
        protected BoneClone clone() throws CloneNotSupportedException {
            //深拷贝需要new操作,来新建对象
            BoneClone clone = (BoneClone) super.clone();
            //新建一个对象表示引用不同的对象
            clone.s = new String(s);
            return clone;
        }

        //构造类
        public BoneClone(){
            s = "s";
        }

        public String getS() {
            return s;
        }

        public void setS(String s) {
            this.s = s;
        }
    }

    BoneClone bc1 = new BoneClone();
    bc1.setS("555");
    BoneClone bc2 = null;
    try {
        bc2 = bc1.clone();
    } catch (CloneNotSupportedException e) {
        e.printStackTrace();
    }
    assert bc2 != null;
    System.out.println(bc2.getS());//555
}

关于clone的建议

经过上面的简单实验,可以发现其实Object自带的clone还算顺手,但是当我们我遇到比较复杂的类的时候,就会显得比较不顺手了,而且对于新手搞不懂异常的时候,就会经常抛出异常,而且需要类型转换,很不是友好。

Effective Java 书上讲到,最好不要去使⽤ clone(),可以使⽤拷⻉构造函数或者拷⻉⼯⼚来拷⻉⼀个对象。

这里可以研究一下Array List的iterator方法。

private static void CloneConstructorTest() {

    class CloneConstructor{
        private String s;

        //构造函数
        public CloneConstructor(){
            s = "";
        }

        public String getS() {
            return s;
        }

        public void setS(String s) {
            this.s = s;
        }

        /**
         * 克隆构造方法,原理与构造方法类似,不同点在于需要获取原始对象数据,并将拷贝对象的数据赋值给拷贝对象
         */
        public CloneConstructor(CloneConstructor original){
            //代替clone方法,
            this.s = original.s;
        }
    }
}

更详细的可参考:blog.csdn.net/j2ee_infini…

其余方法与线程或JVM的GC相关,之后再提。

继承

访问权限

Java中有三个访问权限修饰符:private,protected,public,如果不加访问修饰符,则默认包级可见default。

访问权限修饰符同一个类同一个包不同包的子类不同包的非子类
private
default
protected
public
  • 类可见表示其他类可以用这个类创建对象
  • 成员可见表示其他类可用这个类的实例对象访问到该成员或方法

抽象类与接口

老生常谈的话题了,由于抽象类只能被继承所以他的大部分字段及方法为public。

异同抽象类接口
关键字abstractinterface
方法体抽象方法无方法体,非抽象方法可以存在方法体可以有方法体,default声明的方法必须有方法体
实例化不能被实例化可以被实例化
继承/实现
字段默认默认为public,static,final,不允许定义为private或protected,在java9之后可以定义为private,
方法默认默认为public

抽象类

public abstract class AbstractTest{
    //类声明时带有abstrac则表明这是一个抽象类
    
    private int i;
    
    //抽象方法不可以存在方法体,同时在方法声明时使用abstract则必须将整个类声明为abstract
    abstract void fun1();

    void fun2() {
        //非抽象方法必须存在方法体
    }
}
继承
class AbstractTest1 extends AbstractTest{

    @Override
    void fun1() {
        //必须继承abstract方法
    }
}

接口类

public interface InterfaceTest{
    //接口中的字段和方法默认都是public的,无需添加
    //接口声明常量时必须初始化,且都是static和final的
    static int i = 0;//Modifier 'static' is redundant for interface fields
    final int j = 0;//Modifier 'final' is redundant for interface fields
    public int y = 0;//Modifier 'public' is redundant for interface fields

    void fun1();

    default void fun2(){

    }

    public default void fun3(){
        //Modifier 'public' is redundant for interface methods
    }

}
实例化
InterfaceTest interfaceTest = new InterfaceTest() {
    @Override
    public void fun1() {

    }
};

总结

(参考自:zhuanlan.zhihu.com/p/84593550)

语法层面的区别:

  1. 接口可以提供具体的实现方法,而抽象类只能提供方法名
  2. 接口中的变量类型是单一的(只能是public static final),而抽象类中的变量类型是多种多样的
  3. 接口中不能含有静态代码块和静态方法,但是抽象类中可以
  4. 一个类只能继承一个抽象类,但是可以实现多个接口类。

设计层面的区别:

  1. 抽象类是对实物的抽象,是“是不是”的思想,是IS-A的思想;接口是“有没有”的思想,是HAS-A的思想,比如抽象类:人,如何判断是不是“人”,则是抽象类需要做的事情,而决定你是‘1’还是‘0’则是接口的需要做的事情。
  2. 设计层面不同,对于抽象类,是模板式设计;对于接口类,是辐射式设计。修改抽象类可以选择使用带方法体的非抽象方法,而不影响子类;修改接口类则子类也会跟着修改。

==tips:接口优于抽象类使用,因为不是所有的东西都可以抽象出公共特点,且接口可以多个继承==

super

  • 访问父类的构造函数:可以使用super来访问父类的构造函数,委托父类完成初始化。再调用子类时,一定会调用父类的构造函数,但是一般会调用父类的默认的构造函数,可以使用super调用其他构造函数。
  • 访问父类的成员:如果子类中重写了父类的方法,此时还想调用此方法的话可以通过super方法调用。
/**
 * @author masuo
 * @create 2021/7/14 11:01
 * @Description super
 */
public class SuperExample {

    public static void main(String[] args) {
        SuperExample se = new SuperExample();
        se.superTest();
    }

    public void superTest() {

        Son son = new Son(1,2,3);
        son.fun();
    }

    class Father{
        private int i;
        private int j;

        public Father(){
            //默认构造函数
        }

        public Father(int i,int j){
            //带参数非默认构造函数
            this.i = i;
            this.j = j;
        }

        void fun(){
            System.out.println("father fun");
        }
    }

    class Son extends Father{
        private int i;
        private int j;
        private int x;

        public Son(){
            //默认构造函数
        }

        public Son(int i,int j, int x){
            super(i, j);
            this.x = x;
        }

        @Override
        public void fun() {
            super.fun();
            System.out.println("son fun");
        }
    }
}

重写与重载

区别

名称重写(over write)重载(over load)
存在于继承关系中同一个类中
实现重写父类方法体改变参数个数或类型
@Override

重写

重写存在于继承关系中,指子类实现了一个与父类在方法声明上完全相同的一个方法。

重写需满足里氏替换原则:

  • 子类方法的访问权限必须大于等于父类
  • 子类的返回类型必须是父类返回类型或子类型
  • 子类抛出的异常必须是父类异常的类型或子类型

可以使用@Override来检验自己的方法是不是满足里氏替换原则

private static void overWrite() {
    //发生在父类与子类之间
    class Father extends Object{
        private int i;

        protected void funAccessControl(){
            //默认包级可见
            System.out.println("父类访问控制权限为protected。");
        }

        protected Father funReturnType(){
            //默认包级可见
            System.out.println("父类返回类型为Father");
            return new Father();
        }

        protected void funException()throws Throwable{
            //默认包级可见
            System.out.println("fun");
        }
    }

    class Son extends Father{
        /** 满足里氏替换原则
             * 1.访问控制权限大于等于父类
             * 2.返回类型是父类返回类型或其子类
             * 3.抛出异常为父类异常或其子类
             */

        //            private void funAccessControl(){
        //                //'funAccessControl()' in 'Son' clashes with 'funAccessControl()' in 'Father'; attempting to assign weaker access privileges ('private'); was 'protected'
        //                //本人翻译水平有限,有道翻译为:'Son'中的'funAccessControl()'与'Father'中的'funAccessControl()'冲突;试图分配较弱的访问权限('private');“保护”
        //                System.out.println("子类访问控制权限为private。未通过。");
        //            }

        public void funAccessControl(){
            //
            System.out.println("子类访问控制权限为public。通过。");
        }

        //            public Father funReturnType(){
        //                //Incompatible types. Found: 'java.lang.Object', required: 'Father'
        //                //不兼容的类型,
        //                return new Object();
        //            }

        public Father funReturnType(){
            //
            return new Son();
        }

        public void funException() throws Exception{
            //
        }
    }

    Father son = new Son();
    son.fun();
    son.funAccessControl();

    try {
        son.funException();
    } catch (Throwable throwable) {
        throwable.printStackTrace();
    }

    son.funReturnType();
    System.out.println(son.toString());
}

输出结果:

这是子类没有的父类方法。
子类访问控制权限为public。通过。
子类 funReturnType的返回类型是Son,Father的子类。
JavaBase.OverWriteOROverLoad$1Son@1b6d3586

所以输出顺序为:

本身的方法优先,如果在自身方法中没有找到该方法,则去父类寻找。

在父类中找不到则在往上一级父类中寻找直到首次找到该方法。

总结就是

  • this.fun(this)
  • super.fun(this)
  • this.fun(super)
  • super.fun(super)

重载

存在于同一个类中,指一个方法与此类中已经存在的方法同名,但是参数类型或参数个数或参数顺序中有一个不相同。

返回值不同,但是方法名一样,不算重载。

/**
 * @author masuo
 * @create 2021/7/15 22:37
 * @Description 重载
 */
public class OverLoad {
    void fun(){
        //无参数
    }

    void fun(int i){
        //有一个参数
    }

    void fun(int i,int j){
        //有两个参数
    }

    void fun(String s){
        //有一个参数,类型不同
    }

    String fun(){
        //返回值不同,但是方法名一样,不算重载,不可行
        //'fun()' is already defined in 'JavaBase.OverLoad'
        return "00";
    }
}

容器

概述:首先来说一下,在Java中什么是容器?

在Java中,如果有一个类专门用来存放其他类的对象,这个类就叫容器,或者集合。

容器主要包括Collection和Map两种,Collection是对象的集合,Map键值对的映射。来看一下这两个的结构。

preview

(虚线的方框代表这个类是接口类,实体方框嗲表他是一个可实现类。)

先总结一下自己整理完集合以及自己已掌握的知识做的一张表

存储
Collection数据集合
MapKey-value
底层实现性能重复性排序安全性
ArrayList数组查询快,增删慢可重复不排序线程不安全
LinkedList双向链表增删快,查询慢线程不安全
HashMapK-V数组查询快,增删较慢key可null,不可重复无序线程不安全
LinkedHashMapHashMap+双向链表同HashMap插入顺序和访问顺序根据AccessOrder参数设置线程不安全
TreeMap红黑树增删慢,有序,红黑树线程不安全
ConcurrentHashMapHashMap+锁同HashMap同HashMap同HashMap线程安全
HashSetHashMap无重复
TreeSetTreeMap插入顺序

Collection

主要是单个元素的集合,包括List,set,queue三个接口,三种不同的实现方式。

Collections

在这里需要注意一个Collections类,这个类是一个公共私有类,为什么说他是一个公共私有类,都公共了还怎么私有呢?这里就是关键字private的作用了。我们来看一下Collections的构造函数。

// Suppresses default constructor, ensuring non-instantiability.
private Collections() {
    //正是这个private让他变成一个私有类,不可以被实例化,
    //学到了,如果建立一个公共类但是不想被实例化的话,可以使用私有化构造函数解决
}
Collection和Collections有什么不同?
  • collection是一个接口,提供了提供了集合对象的基础通用接口
  • collections是一个公共私有类,不能被实例化,但是包含很多静态类。想要使用她的方法,我们可以使用类名+方法名(参数)的方法去调用。

List

List的特点在于元素可重复,主要分为ArrayList和LinkedList,还有一个vector类。

public static void main(String[] args) {
    List<String> lv = new Vector<>();

    List<String> la = new ArrayList<>();

    List<String> ll = new LinkedList<>();
    
    List<String> ls = new Stack<>();
}
Array List

Array List底层由数组完成,且他是一个动态增长的数组,初始长度为10.

private static final int DEFAULT_CAPACITY = 10;//ArrayList数组的默认长度为10

在Java中声明一个数组是需要长度的,所以Java中数组的长度是固定的,但是Array List的长度是不固定的。来看一下它是如何实现动态增长的吧。

首先他有两个构造函数来应对有参构造以及无参构造,当然他不止这两个构造函数,还有上面提到的clone构造函数。

/**
 * Constructs an empty list with the specified initial capacity.
 * 有参构造,使用特殊的初始化容量构造一个空的list,在这里特殊的初始化容量就是传进来的参数
 * @param  initialCapacity  the initial capacity of the list
 * @throws IllegalArgumentException if the specified initial capacity
 *         is negative
 */
//这个方法在我们这个样声明时调用:List<String> al1 = new ArrayList<>(10);
public ArrayList(int initialCapacity) {
    if (initialCapacity > 0) {
        this.elementData = new Object[initialCapacity];
    } else if (initialCapacity == 0) {
        this.elementData = EMPTY_ELEMENTDATA;
    } else {
        throw new IllegalArgumentException("Illegal Capacity: "+
                                           initialCapacity);
    }
}

/**
 * Constructs an empty list with an initial capacity of ten.
 * 使用默认初始化容量10构造一个空的list
 */
//这个方法在我们这个样声明时调用:List<String> al2 = new ArrayList<>();
public ArrayList() {
    this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}

可以看到,这两个构造函数还是蛮简单的,很容易懂.

接下来看看当我们往数组中添加数据时会发生什么。

private static void ArrayListTest() {
    List<String> al1 = new ArrayList<>(2);
    List<String> al2 = new ArrayList<>();//第一步,初始化进入无参构造方法
    al2.add("1");//第二步,
    al2.add("2");
    al2.add("3");
    al2.add("4");
    al2.add("5");
    al2.add("6");
    al2.add("7");
    al2.add("8");
    al2.add("9");
    al2.add("10");//
    al2.add("11");
    al2.add("12");
    al2.add("13");
    al2.add("14");
    al2.add("15");
    al2.add("16");
}

第一步

//初始化时会先进入这个构造方法,elementData时用来存放数据的,非常重要,要时刻关注她的变化。

public ArrayList() {
    this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
    //这个时候elementdata的长度是0,与此同时modCount被赋值为0
}

//DEFAULTCAPACITY_EMPTY_ELEMENTDATA:默认初始化为一个空数组
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};

第二步

//调用add函数,在add函数中,
public boolean add(E e) {
    //执行ensureCapacityInternal:确保内部容量,因为本次需要add一个数据,在刚进入add的时候,此时数据还没被加到数组中,需要判断数组容量是否足够,所以需要将size+1在进行判断,判断过程在第三步
    //足够则执行下一步:elementData[size++] = e;,
    //不足够的话,会调用grow,下面会提到
    
    //第三步
    ensureCapacityInternal(size + 1);  // Increments modCount!!
    elementData[size++] = e;
    return true;
}

第三步

//ensureCapacityInternal:确保内部容量足够,之后进入 calculateCapacity 方法
 private void ensureCapacityInternal(int minCapacity) {
     //这里的两个参数分别代表存储数据的数组elementData,存储数据最低需要的容量minCapacity
     
     //进入第四步
     ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
 }

第四步

//calculateCapacity:计算容量,在这一步会算出最低所需容量并返回,之后会返回  ensureCapacityInternal 方法,并进入 ensureExplicitCapacity 这个方法
private static int calculateCapacity(Object[] elementData, int minCapacity) {
    //首先判断是不是第一次添加数据,如果是第一次则从默认数组长度与初始化时设置的数组长度中返回较大的数据作为elementdata的长度
    if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
        return Math.max(DEFAULT_CAPACITY, minCapacity);
    }
    return minCapacity;
    
    //之后进入第五步
}

第五步

//ensureExplicitCapacity:确保显式容量,在这一步中,会确认elementdata的长度
private void ensureExplicitCapacity(int minCapacity) {
    //这个参数是指当前列表被修改的次数
    modCount++;

    // overflow-conscious code
    //注意:这里的minCapacity是指数组中数组的个数,即size,而elementData.length是数组的长度,数组的长度声明之后是不能变的,这两个是不相等的,在这里相比较的就是这两个数值,当然这个size是+1之后的size
    //当size的大小大于length的时候,说明数组长度已经不够了,需要扩容
    if (minCapacity - elementData.length > 0)
        //第六步
        grow(minCapacity);
}

第六步

//grow:扩容机制是如何运行的呢?下面我们来一起看看吧。
private void grow(int minCapacity) {
    // overflow-conscious code
    int oldCapacity = elementData.length;//旧的容量等于还没扩容的elementdata的数组长度
    int newCapacity = oldCapacity + (oldCapacity >> 1);//新的容量等于旧容量的1.5倍,至于为什么是1.5倍,需要去了解一下位运算的'>>'运算,
    if (newCapacity - minCapacity < 0)
        //如果新容量小于新容量,至于这个你可能会产生一个疑问,怎么可能,都1.5倍了,但是别忘了,还有容量为0的时候呢,0的1.5倍还是0哦。
        newCapacity = minCapacity;
    	//将minCapacity赋值给newCapacity,这里minCapacity最小都会是10,不会再小了
    
    
    if (newCapacity - MAX_ARRAY_SIZE > 0)
        //这一步是保证数组长度不会超过int的承受范围,如果你的数组有需求,可以更长,这在现在就不细讲了,总之你要知道,他最长的长度是整数的最大值,但是为了避免出现错误才减8,如OutOfMenmory,
        newCapacity = hugeCapacity(minCapacity);
    // minCapacity is usually close to size, so this is a win:
    
    
    //将数组中的数据复制给扩容后的数组。数组长度变大
    elementData = Arrays.copyOf(elementData, newCapacity);
}

private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;

以上就是ArrayList的初始化以及扩容机制。希望你能看懂。

优缺点

使用数组作为底层的优点就是访问速度够快,但是增删慢。因为数组是有序的放在内存上的,只需按照下标去找就可以直接找到。

与vector的区别

vector了解即可,都说这是一个已经过时的知识点。(但是还有很多参考价值)

  • 线程安全:vector是线程安全的,ArrayList是非线程安全的
  • 性能:Array List性能优于vector,因为他在操作数据时会上锁,所以很费时间
  • 扩容机制:vector每次扩容都会增加一倍,而ArrayList每次只会扩大1.5倍。
Linked List

LinkedList底层是由双向链表实现的,没有初始容量,链表嘛,想要扩容往下寻址链接即可。

先来简单看下源码吧,到了这一步,看源码是了解他最快的方式。

//size代表数据量,同ArrayList的size
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.
 */
public LinkedList() {
}

/** 有参构造函数
 * Constructs a list containing the elements of the specified
 * collection, in the order they are returned by the collection's
 * iterator.
 *
 * @param  c the collection whose elements are to be placed into this list
 * @throws NullPointerException if the specified collection is null
 */
public LinkedList(Collection<? extends E> c) {
    this();
    addAll(c);
}

这里面出现最多的就是这个Node了,那么这个Node又是什么呢?

//这个Node是LinkedList的内部私有类,含有三个变量以及一个构造函数,
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;//指向前一个
    }
}

嗯,就是这样的,前后一个节点,中间是自己。

来个例子看看吧。

private static void LinkedListTest() {
    System.out.println("linked list test");

    //第一步,声明一下,看看如何初始化的
    List<String> ls = new LinkedList<>();

    //加数据,因为有前后中,所以数据大于等于3就行,
    //第二步
    ls.add("1");
    ls.add("2");
    ls.add("3");
    ls.add("4");
    ls.add("5");

    System.out.println(ls);
}

第一步

/** 进入一个无参构造函数
 * Constructs an empty list.
 */
public LinkedList() {
}

//到声明结束与ArrayList大致一致

第二步

/** 往数组尾部加数据
 * 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})
 */
public boolean add(E e) {
    //第三步
    linkLast(e);
    return true;
}

第三步

/** 将e链接为最后一个元素
 * Links e as last element.
 */
void linkLast(E e) {
    final Node<E> l = last;//null
    final Node<E> newNode = new Node<>(l, e, null);//这一步就是将自己放入里面
    last = newNode;//之后将自己变成上一个节点,毕竟自己已经被放进来了,就老了
    //到这里,前后基本都赋值完成了
    
    //之后,这里是判断是不是第一次执行,第一次执行需要给first赋值,将第一个插入的同时也将他变成第一个节点,如果不是第一次,将新节点链接到上一个节点
    if (l == null)
        first = newNode;
    else
        l.next = newNode;
    //容量以及操作数+1
    size++;
    modCount++;
}

后面的就是重复第三步了。

具体可参考:zhuanlan.zhihu.com/p/28101975

优缺点

由于底层是用双向链表实现的,可以看到增删改都比较简单(只需将删除节点的前后指向修改一下即可,并将本节点使得前后指向为null),但是查看的时候需要遍历数组,如果你要找的节点在最后一个,那好吧你需要全部循环一遍,但是使用数组为底层的时候只需找到相应下标即可。

还可以用作栈,队列和双向队列。

Set

同样,Set有两个子类HashSet和TreeSet,HashSet又包括LinkedHashSet,在此之前需要我们先掌握Map相关的知识,所以尽量先看看Map吧。

先来看一下结构图。

image-20210726144110781

HashSet

来看一下源码吧,如你不想通过源码来了解一个类,你还可以通过他顶部的注释来了解她的特性以及用法,我们来看一下

/**
 * A collection that contains no duplicate elements.(无重复对象的集合)  
 * More formally, sets
 * contain no pair of elements <code>e1</code> and <code>e2</code> such that
 * <code>e1.equals(e2)</code>, and at most one null element(最多有一个null对象). 
 * As implied by
 * its name, this interface models the mathematical <i>set</i> abstraction.
 *
 * <p>The <tt>Set</tt> interface places additional stipulations, beyond those
 * inherited from the <tt>Collection</tt> interface, on the contracts of all
 * constructors and on the contracts of the <tt>add</tt>, <tt>equals</tt> and
 * <tt>hashCode</tt> methods.  Declarations for other inherited methods are
 * also included here for convenience.  (The specifications accompanying these
 * declarations have been tailored to the <tt>Set</tt> interface, but they do
 * not contain any additional stipulations.)
 *
 * Note that this implementation is not synchronized.不同步的
 */
static final long serialVersionUID = -5024744406713321676L;

private transient HashMap<E,Object> map;

// Dummy value to associate with an Object in the backing Map
// 与后台映射中的对象关联的虚拟值,即所有的value都是(Present)object,毕竟Hash Set是以Hash Map为底层实现的
private static final Object PRESENT = new Object();


public HashSet() {
    map = new HashMap<>();
}


public HashSet(Collection<? extends E> c) {
    map = new HashMap<>(Math.max((int) (c.size()/.75f) + 1, 16));
    addAll(c);
}


public HashSet(int initialCapacity, float loadFactor) {
    map = new HashMap<>(initialCapacity, loadFactor);
}


public HashSet(int initialCapacity) {
    map = new HashMap<>(initialCapacity);
}


HashSet(int initialCapacity, float loadFactor, boolean dummy) {
    map = new LinkedHashMap<>(initialCapacity, loadFactor);
}

可以看到,到处都是HashMap的知识,所以先了解HashMap是没错的。

特性

  • 只允许一个null(跟HashMap中key只允许有一个null相同)
  • 没有重复对象(值相等)
  • 不保证迭代顺序(同HashMap)
  • 不同步(线程不安全)
TreeSet

TreeSet与HashSet的不同就在于TreeSet是有序的,而且她的底层是Tree Map

Queue

Map

我们都知道Map是以键值对<Key,Value>的形式保存数据的,

public interface Map<K,V>

在Map中最重要的便是如下三个集合,在这里面你可能会产生的一个疑问就是K,V分别是什么?

这么说,这是Java5就已经存在的一个特性了-泛型,具体可参考:www.jianshu.com/p/41a7a9755…

// Views

//key,键
Set<K> keySet();

//value,值
Collection<V> values();

//entry,键值对
Set<Map.Entry<K, V>> entrySet();

//这里这个Entry是Map的一个内部接口类
interface Entry<K,V> {
    /**
     * Returns the key corresponding to this entry.
     */
    K getKey();

    /**
     * Returns the value corresponding to this entry.  
     */
    V getValue();

    /**
     * Replaces the value corresponding to this entry with the specified
     * value (optional operation).  
     */
    V setValue(V value);

    /**
     * Compares the specified object with this entry for equality.
         
     */
    boolean equals(Object o);

    /**
     * Returns the hash code value for this map entry.  
     */
    int hashCode();

    /**
     * Returns a comparator that compares {@link Map.Entry} in natural order on key.
     */
    public static <K extends Comparable<? super K>, V> Comparator<Map.Entry<K,V>> comparingByKey() {
        return (Comparator<Map.Entry<K, V>> & Serializable)
            (c1, c2) -> c1.getKey().compareTo(c2.getKey());
    }

    /**
     * Returns a comparator that compares {@link Map.Entry} in natural order on value.
     */
    public static <K, V extends Comparable<? super V>> Comparator<Map.Entry<K,V>> comparingByValue() {
        return (Comparator<Map.Entry<K, V>> & Serializable)
            (c1, c2) -> c1.getValue().compareTo(c2.getValue());
    }

    /**
     * Returns a comparator that compares {@link Map.Entry} by key using the given
     */
    public static <K, V> Comparator<Map.Entry<K, V>> comparingByKey(Comparator<? super K> cmp) {
        Objects.requireNonNull(cmp);
        return (Comparator<Map.Entry<K, V>> & Serializable)
            (c1, c2) -> cmp.compare(c1.getKey(), c2.getKey());
    }

    /**
     * Returns a comparator that compares {@link Map.Entry} by value using the given
     */
    public static <K, V> Comparator<Map.Entry<K, V>> comparingByValue(Comparator<? super V> cmp) {
        Objects.requireNonNull(cmp);
        return (Comparator<Map.Entry<K, V>> & Serializable)
            (c1, c2) -> cmp.compare(c1.getValue(), c2.getValue());
    }
}

根据Set和Collection的特性得知,key和entry都是没有重复的,值可以重复。键与值都可以为null。

以下都是我们在Map的子类中经常用到的,或者知道的但不一定用过的。不需要过多的解释了。

/**
 * Returns the number of key-value mappings in this map.  
 *
 * @return the number of key-value mappings in this map
 */
int size();

/**
 * Returns <tt>true</tt> if this map contains no key-value mappings.
 *
 * @return <tt>true</tt> if this map contains no key-value mappings
 */
boolean isEmpty();

/**
 * Returns <tt>true</tt> if this map contains a mapping for the specified
 * key.  
 */
boolean containsKey(Object key);

/**
 * Returns <tt>true</tt> if this map maps one or more keys to the
 * specified value.  
 */
boolean containsValue(Object value);

/**
 * Returns the value to which the specified key is mapped,
 * or {@code null} if this map contains no mapping for the key.
 */
V get(Object key);

// Modification Operations

/**
 * Associates the specified value with the specified key in this map
 * (optional operation).  
 */
V put(K key, V value);

/**
 * Removes the mapping for a key from this map if it is present
 * (optional operation).   
 */
V remove(Object key);


// Bulk Operations

/**
 * Copies all of the mappings from the specified map to this map
 * (optional operation).  
 */
void putAll(Map<? extends K, ? extends V> m);

/**
 * Removes all of the mappings from this map (optional operation).
 * The map will be empty after this call returns.
 *
 * @throws UnsupportedOperationException if the <tt>clear</tt> operation
 *         is not supported by this map
 */
void clear();

一下是Map的子类或子类的子类的声明方式,至于这里为什么使用Map这个大父类来声明而不是使用自己的类名来声明,是因为这样可以使用Map或父类的方法。

//Map的子类或子类的子类
Map<Integer,String> m1 = new HashMap<>();

Map<Integer,String> m2 = new TreeMap<>();

Map<Integer,String> m3 = new LinkedHashMap<>();

Map<Integer,String> m4 = new Hashtable<>();

Map<Integer,String> m5 = new ConcurrentHashMap<>();

但是Map是如何实现以键值对存储数据的呢?这么做又有什么好处和坏处呢

实现

通过源码得知,Map是三个集合的共同体现。通过没有重复的键(因为键具有互异性)与可重复的值映射完成Map的设计,这实际就是将键作为数组,数组中存储引用的对象。通常情况下,Map不具备有序性(TreeMap除外)。

Map主要包括HashMap和LinkedHashMap,TreeMap,也是我们主要需要了解与掌握的类。以及需要了解以及会使用的Tree Map和Concurrent Hash Map类。

Hash Map

Hash Map是不能有序输出的,即不能按照插入的顺序输出,输出顺序可能是无序的。

你会发现在Map中有很多Hash,那么什么是Hash呢?

Hash
什么是Hash?

Hash又称哈希,散列,是一种算法。实现是通过输入任意长度的值,通过哈希算法变成固定长度的输出,这个由任意长度的输入固定长度的输出映射规则就是hash算法。

hash的特点
  • 不可逆,即根据算出的hash值不能得到原始数据
  • 散列,数据要足够分散,这也是他叫散列的原因

再好的算法,在数据基数非常大的前提下也会变得不堪一击,再好的散列,遇到足够多的数据也会不那么散列,此时就会出现冲突碰撞的情况,那么如何解决冲突与碰撞就成了新的问题。

冲突的产生
  • 数据量大
  • 散列范围小
解决冲突的方法

hash算法是一定会有冲突的,那么如果我们如果遇到了hash冲突需要解决的时候应该怎么处理呢?比较常用的算法是链地址法开放地址法

  • 链地址法,也叫拉链法,实现原理是将冲突的数据像糖葫芦一样串起来,即当遇到冲突时,将产生冲突的数据连接到hash值相同的数据最后面,形成链表。

  • 开放地址法,也叫开放寻址法,包括线性探测法,二次hash,双重散列法。开放寻址法实现原理是当产生冲突时,往下寻找空地址并将数据放入其中。

具体有关Hash的讲解可参考:blog.csdn.net/woshimaxiao…

我们知道了Hash的原理之后,再来看由此而生的HashMap,HashMap主要包括两部分,数组和链表,数组是HashMap的主体,链表则是为了解决冲突而存在的(JDK1.8)。

常量

下面我们来深入探究一下,Hash Map的内部到底是什么样的吧。

首先从类的定义中我们可以看到他继承自AbstractMap,实现了Map,Cloneable,Serializable三个接口,这三个接口中Map是我们刚才看到的,Cloneable是我们之前用到的,至于Serializable是什么意思吗,就是对象序列化的接口,只有实现了这个接口,它的对象才能被序列化,至于具体的作用可以参考这篇文章:baijiahao.baidu.com/s?id=163330…

public class HashMap<K,V> extends AbstractMap<K,V>
    implements Map<K,V>, Cloneable, Serializable {
    
    //这是她的序列化标识,被transient关键字所标记的变量与方法不会被序列化,序列化时为了能高效快捷的存储在存储介质上,
    private static final long serialVersionUID = 362498820763181265L;

在这里它定义了很多常量,我们来看一下。

/**
 * The default initial capacity - MUST be a power of two.
 * 初始化容量默认是1的二进制向左移四位。1的二进制是00000001,向左移四位变成00010000,等于16
 * 初始容量不大不小,刚刚合适,太大的话很占空间,太小的话,又容易导致空间不够二直接进行扩容
 */
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16

/**
 * The maximum capacity, used if a higher value is implicitly specified
 * by either of the constructors with arguments.
 * MUST be a power of two <= 1<<30.
 * 最大容量:1的二进制向左移30位,00000000 00000000 00000000 00000001
 * 							 01000000 00000000 00000000 00000000 = 1 073 741 824
 */
static final int MAXIMUM_CAPACITY = 1 << 30;

/**
 * The load factor used when none specified in constructor.
 * 加载因子:用于控制剩余空间,比如你需要8个空间,他就会给你8/0.75 = 11个空间
 * 加载因子设为0.75是有原因的,设置的太小的化,剩余空间太多容易造成浪费,设置的太大的话,又容易导致
 * 复制的时候速度很慢
 */
static final float DEFAULT_LOAD_FACTOR = 0.75f;

/**
 * The bin count threshold for using a tree rather than list for a
 * bin.  Bins are converted to trees when adding an element to a
 * bin with at least this many nodes. The value must be greater
 * than 2 and should be at least 8 to mesh with assumptions in
 * tree removal about conversion back to plain bins upon
 * shrinkage.
 * 这个是Java8中的最大更新点,将hashmap的数据结构由【数组+链表】变成了【数组+链表+红黑树】
 * 这个就是判断该条链表是否需要树化的判断条件,当链表中元素>=8时会树化,
 * 至于为什么是8,这个网上的答案一艘一大篓,
 * https://blog.csdn.net/F1004145107/article/details/105904975/
 * 可以看看这篇
 */
static final int TREEIFY_THRESHOLD = 8;

/**
 * The bin count threshold for untreeifying a (split) bin during a
 * resize operation. Should be less than TREEIFY_THRESHOLD, and at
 * most 6 to mesh with shrinkage detection under removal.
 * 这个就跟上面树化是相反的了,当链表中的元素<=6时,就会变成普通链表
 */
static final int UNTREEIFY_THRESHOLD = 6;

/**
 * The smallest table capacity for which bins may be treeified.
 * (Otherwise the table is resized if too many nodes in a bin.)
 * Should be at least 4 * TREEIFY_THRESHOLD to avoid conflicts
 * between resizing and treeification thresholds.
 * 红黑树化所需的最小容量,即当数据总量小于64的时候就算一个节点上的数据超过8条都不会树化
 */
static final int MIN_TREEIFY_CAPACITY = 64;
构造函数

Hash Map一共有四个构造函数,来看源码

//带参数,初始化容量与加载因子,
//Map<Integer,String> m = new HashMap<>(10,0.6f);
public HashMap(int initialCapacity, float loadFactor) {
    if (initialCapacity < 0)
        throw new IllegalArgumentException("Illegal initial capacity: " +
                                           initialCapacity);
    if (initialCapacity > MAXIMUM_CAPACITY)
        initialCapacity = MAXIMUM_CAPACITY;
    if (loadFactor <= 0 || Float.isNaN(loadFactor))
        throw new IllegalArgumentException("Illegal load factor: " +
                                           loadFactor);
    this.loadFactor = loadFactor;
    //在这里,这个threshold是有什么用的呢?,我们来看一下tableSizeFor这个函数干了什么
    this.threshold = tableSizeFor(initialCapacity);
}

//Returns a power of two size for the given target capacity.
//官方注释:返回一个提供的容量的两倍容量,就是说你传一个10的话,他就返回20,
 static final int tableSizeFor(int cap) {
     int n = cap - 1;
     n |= n >>> 1;
     n |= n >>> 2;
     n |= n >>> 4;
     n |= n >>> 8;
     n |= n >>> 16;
     //这里还设置了一个判断防止返回的值为负数或者0
     return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
 }
/**
 * Constructs an empty <tt>HashMap</tt> with the specified initial
 * capacity and the default load factor (0.75).
 * 只有初始化容量的构造函数
 * Map<Integer,String> m1 = new HashMap<>(10);
 * 从代码中可以看出,调用此函数时系统会默认分配默认的加载因子,同时调用上一个构造函数
 */
public HashMap(int initialCapacity) {
    this(initialCapacity, DEFAULT_LOAD_FACTOR);
}

/**
 * Constructs an empty <tt>HashMap</tt> with the default initial capacity
 * (16) and the default load factor (0.75).
 * 无参,全部为默认的参数
 */
public HashMap() {
    this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}

/**
 * Constructs a new <tt>HashMap</tt> with the same mappings as the
 * specified <tt>Map</tt>.  The <tt>HashMap</tt> is created with
 * default load factor (0.75) and an initial capacity sufficient to
 * hold the mappings in the specified <tt>Map</tt>.
 *
 * @param   m the map whose mappings are to be placed in this map
 * @throws  NullPointerException if the specified map is null
 * 此构造函数未copy函数,即copy传进来的参数的结构与数据,只要是Map的子类或者子类的子类就可以
 */
public HashMap(Map<? extends K, ? extends V> m) {
    this.loadFactor = DEFAULT_LOAD_FACTOR;
    putMapEntries(m, false);
}
初始化
Map<Integer,String> m1 = new HashMap<>(10);//设置初始化容量为10

//首先进入classloader函数,这个之后再说,
//其次进入,带一个参数的hashmap构造函数HashMap(int initialCapacity)
public HashMap(int initialCapacity) {
    //这个函数调用带两个参数的构造函数HashMap(int initialCapacity, float loadFactor)
    this(initialCapacity, DEFAULT_LOAD_FACTOR);
}

//
public HashMap(int initialCapacity, float loadFactor) {
    //当初始化容量小于0,抛出异常
    if (initialCapacity < 0)
        throw new IllegalArgumentException("Illegal initial capacity: " +
                                           initialCapacity);
    //当初始化容量大于大于最大容量时,将他限制在最大容量
    if (initialCapacity > MAXIMUM_CAPACITY)
        initialCapacity = MAXIMUM_CAPACITY;
    //当加载因子小于0,抛出异常
    if (loadFactor <= 0 || Float.isNaN(loadFactor))
        throw new IllegalArgumentException("Illegal load factor: " +
                                           loadFactor);
    //加载因子赋值
    this.loadFactor = loadFactor;
    //根据初始化容量设置threshold,这里threshold不是容量,是下一次更新容量要设置的容量
    this.threshold = tableSizeFor(initialCapacity);
}

//设置threshold
static final int tableSizeFor(int cap) {
    
    int n = cap - 1;//10-1=9,二进制为:1001
    //>>>代表无符号右移运算,|= 代表 +=
    n |= n >>> 1;//n >>> 1 = 4,转换成二进制为:0100,1001 | 0100=1101=13=n
    n |= n >>> 2;//n >>> 2 = 0011=3,0011 | 1101 = 1111 = 15
    n |= n >>> 4;//根据‘|’的运算特性,下面在运算都只会是1111,
    n |= n >>> 8;
    n |= n >>> 16;
    //到此n=15,下面这句话是n小于0则返回1,否则返回(n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1,
    //所以最后返回n+1=16,
    return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
}
//至此,初始化完成。
put(K,V)
public V put(K key, V value) {
    return putVal(hash(key), key, value, false, true);
}

//hash:key的hash值
//onlyIfAbsent:当为真时,不改变已存在的数据
//evict:当初始化的时候是false,这里传入的是true说明不是初始化,
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
    Node<K,V>[] tab; Node<K,V> p; int n, i;
    
    //第一次put,成立并且为tab与n赋值
    if ((tab = table) == null || (n = tab.length) == 0)
        n = (tab = resize()).length;
    //这里是判断是否是第一次put,并且为p赋值,下面会用到这个
    //(n - 1) & hash:这个值等于hash,至于为什么会这样,因为n是2的n次方,这样n-1的二进制就全是1,通过&运算,就会得到的值等于hash,
    if ((p = tab[i = (n - 1) & hash]) == null)
        tab[i] = newNode(hash, key, value, null);
    else {
        //进入这的都是hash值相同,需要成链的数据
        Node<K,V> e; K k;
        if (p.hash == hash &&
            ((k = p.key) == key || (key != null && key.equals(k))))
            //key值相同,覆盖
            e = p;
        else if (p instanceof TreeNode)
            e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
        else {
            //循环,注意这里是从第一个节点开始
            for (int binCount = 0; ; ++binCount) {
                //这里p是hash值等于hash的节点的
                if ((e = p.next) == null) {
                    //将新节点设置为上一节点的下一节点,即尾插,这也是java8的新特点之一
                    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)
        resize();
    afterNodeInsertion(evict);
    return null;
}
扩容

HashMap扩容,到这里我已经没有场外援助了,他们大多都是以老版Java为例讲的扩容,到这里我只能孤军奋战了,不过也是时候检验一下我的成果了。

final Node<K,V>[] resize() {
    
    //首先,不像Java7,java7中传入了上一个table的容量
    
    //声明一个节点来接收旧的hashmap的数据表
    Node<K,V>[] oldTab = table;
    
    int oldCap = (oldTab == null) ? 0 : oldTab.length;
    //旧表的下一个容量,就是旧表要更新时需要设置的容量
    int oldThr = threshold;
    
    //声明新的
    int newCap, newThr = 0;
    
    //oldCap是旧容量的长度
    if (oldCap > 0) {
        if (oldCap >= MAXIMUM_CAPACITY) {
            //这里由于旧表容量已经非常接近int类型的极限,所以这里只能返回int的最大值
            threshold = Integer.MAX_VALUE;
            return oldTab;
        }
        //这里是判断新的容量不大于设置的最大容量,旧的容量大于默认初始化容量
        else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                 oldCap >= DEFAULT_INITIAL_CAPACITY)
            //箭头向左,左移运算,乘以2,容量扩大一倍,
            newThr = oldThr << 1; // double threshold
    }
    //oldThr是旧容量的下一个容量,即二倍的他,上面有提到过,下面这两个都很简单
    //判断条件之后再说
    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赋值
    threshold = newThr;
    
    
    //clone的过程,有兴趣的同学可以看一下
    @SuppressWarnings({"rawtypes","unchecked"})
    Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
    table = newTab;
    //下面就是将旧的数据一个一个复制到新的map中,
    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;
}

那什么时候才会调用resize()方法呢?在我们的容量等于threshold这个值的时候就会进行扩容,此时在putVal的最后会判断(++size)的值是否大于threshold,如果是的话就调用扩容函数。

  • putMapEntries
//
final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) {
    int s = m.size();
    if (s > 0) {
        if (table == null) { // pre-size
            float ft = ((float)s / loadFactor) + 1.0F;
            int t = ((ft < (float)MAXIMUM_CAPACITY) ?
                     (int)ft : MAXIMUM_CAPACITY);
            if (t > threshold)
                threshold = tableSizeFor(t);
        }
        else if (s > threshold)
            //当要克隆的数据量大于
            resize();//这里
        for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) {
            K key = e.getKey();
            V value = e.getValue();
            putVal(hash(key), key, value, false, evict);
        }
    }
}


//当我们需要clone一个map的时候才会调用这个函数,一共有三个调用这个函数地方,都是clone一个map
public HashMap(Map<? extends K, ? extends V> m) {
    this.loadFactor = DEFAULT_LOAD_FACTOR;
    putMapEntries(m, false);
}

在Java8中,可以看到的改变就是增加了红黑树来提升查询效率,再就是将链表的插入改成了尾插法。

至于Java8为什么不适用头插法的原因之一是因为头插会造成链表死链,参考:blog.csdn.net/chenyiminna… 。原因之二是因为Java7使用头插是考虑到了热点数据的点(最后插入的数据更早用到),但是因为扩容机制的原因,会导致排序失去作用,所以自然这点也就没有用了。

以上就是关于Hash Map的个人理解(部分)了,走了一遍源码,还是有很多地方没走到,但是对于Hash Map有了一个很大了解,下一步就是了解她的红黑树结构,先去了解什么是红黑树吧,最后来看源码会轻松很多。

性能表现

由于是以数组为主体,所以查询很快,但是增删慢。但是具体情况视具体情况而定。只能说数组在查询上非常有优势,因为是下标查询,时间复杂度为O(1),Hash Map本身是个K-V的数组,但是为了解决各种冲突演变成了K-V数组+链表的结构,而链表又具有增删快速的特性,所以综上来看的话,以数组为主,查询快,在主体上增删数据较慢,在链表上增删较快,查询较慢。

Linked Hash Map

Linked Hash Map是一个以双向链表。LinkedHashMap=HashMap+双向链表,实现双向链表是为了记录节点的插入顺序,这样就可以实现有序插入和输出。

更多详情参考:zhuanlan.zhihu.com/p/34490361

看一下Linked Hash Map的源码,继承自Hash Map,实现了Map类。

public class LinkedHashMap<K,V>
    extends HashMap<K,V>
    implements Map<K,V>

看如下代码,Linked Hash Map为了实现双向链表写了哪些代码吧

//首先就是这个entry,它继承自Hash Map的Node类,又自带两个前后节点,在Hash Map中他只有一个next的节点
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);
    }
}

//其次
/**
 * The head (eldest) of the doubly linked list.
 * 头部,最先被插入的节点,
 */
transient LinkedHashMap.Entry<K,V> head;

/**
 * The tail (youngest) of the doubly linked list.
 * 尾部,最后被插入的节点
 */
transient LinkedHashMap.Entry<K,V> tail;

image-20210722192940676

再来看Linked Hash Map的构造函数,一共五个构造函数,同Hash Map,有带参和不带参的。

/**
 * Constructs an empty insertion-ordered <tt>LinkedHashMap</tt> instance
 * with the specified initial capacity and load factor.
 *
 * @param  initialCapacity the initial capacity
 * @param  loadFactor      the load factor
 * @throws IllegalArgumentException if the initial capacity is negative
 *         or the load factor is nonpositive
 */
public LinkedHashMap(int initialCapacity, float loadFactor) {
    //这里指向HashMap的双参构造函数
    super(initialCapacity, loadFactor);
    //决定了顺序,默认为false,此时维护的是插入的顺序
    accessOrder = false;
}

/**
 * Constructs an empty insertion-ordered <tt>LinkedHashMap</tt> instance
 * with the specified initial capacity and a default load factor (0.75).
 *
 * @param  initialCapacity the initial capacity
 * @throws IllegalArgumentException if the initial capacity is negative
 */
public LinkedHashMap(int initialCapacity) {
    super(initialCapacity);
    accessOrder = false;
}

/**
 * Constructs an empty insertion-ordered <tt>LinkedHashMap</tt> instance
 * with the default initial capacity (16) and load factor (0.75).
 */
public LinkedHashMap() {
    super();
    accessOrder = false;
}

/**
 * Constructs an insertion-ordered <tt>LinkedHashMap</tt> instance with
 * the same mappings as the specified map.  The <tt>LinkedHashMap</tt>
 * instance is created with a default load factor (0.75) and an initial
 * capacity sufficient to hold the mappings in the specified map.
 *
 * @param  m the map whose mappings are to be placed in this map
 * @throws NullPointerException if the specified map is null
 */
public LinkedHashMap(Map<? extends K, ? extends V> m) {
    super();
    accessOrder = false;
    putMapEntries(m, false);
}

/**
 * Constructs an empty <tt>LinkedHashMap</tt> instance with the
 * specified initial capacity, load factor and ordering mode.
 *
 * @param  initialCapacity the initial capacity
 * @param  loadFactor      the load factor
 * @param  accessOrder     the ordering mode - <tt>true</tt> for
 *         access-order, <tt>false</tt> for insertion-order
 * @throws IllegalArgumentException if the initial capacity is negative
 *         or the load factor is nonpositive
 */
public LinkedHashMap(int initialCapacity,
                     float loadFactor,
                     boolean accessOrder) {
    super(initialCapacity, loadFactor);
    this.accessOrder = accessOrder;
}

通过以上代码,可以发现他除了按照HashMap的结构存储数据之外,还通过双向链表将数据连接起来,如图所示(这是头插法,即java1.7之前)

img

引自:blog.csdn.net/u012860938/…

Tree Map

先看类

public class TreeMap<K,V>
    extends AbstractMap<K,V>//继承自AbstractMap,大多都是继承自这个
    implements NavigableMap<K,V>, Cloneable, java.io.Serializable
    //实现了以上三个接口,分别是?,可clone,可序列化第一个第一次见
    
public interface NavigableMap<K,V> extends SortedMap<K,V> 
    //往下查看看到这个接口继承自SortedMap,这就使得TreeMap间接继承了SortedMap,使得它有序性得以保障

再来看一下常量

//比较器
private final Comparator<? super K> comparator;

//节点,k-v对
private transient Entry<K,V> root;

/**
 * The number of entries in the tree
 */
private transient int size = 0;

/**
 * The number of structural modifications to the tree.
 */
private transient int modCount = 0;

构造函数

public TreeMap() {
    comparator = null;
}

/**
 * Constructs a new, empty tree map, ordered according to the given
 * comparator.  
 */
public TreeMap(Comparator<? super K> comparator) {
    this.comparator = comparator;
}

/**
 * Constructs a new tree map containing the same mappings as the given
 * map, ordered according to the <em>natural ordering</em> of its keys.
 * All keys inserted into the new map must implement the {@link
 * Comparable} interface.  
 */
public TreeMap(Map<? extends K, ? extends V> m) {
    comparator = null;
    putAll(m);
}

/**
 * Constructs a new tree map containing the same mappings and
 * using the same ordering as the specified sorted map.  This
 * method runs in linear time.
 */
public TreeMap(SortedMap<K, ? extends V> m) {
    comparator = m.comparator();
    try {
        buildFromSorted(m.size(), m.entrySet().iterator(), null, null);
    } catch (java.io.IOException cannotHappen) {
    } catch (ClassNotFoundException cannotHappen) {
    }
}

基于红黑树实现的Tree Map自带排序,但是了解不多,暂不多说。下次一定。

Concurrent Hash Map

image-20210726154104842

以上就是Concurrent Hash Map的结构。

在Concurrent HashMap的文档开头提到,

存储结构:

image-20210726154519429

实现与HashMap类似,唯一的不同是他采用了分段锁(Segment)实现,每个分段锁维护着几个桶(Hash Entry),多个线程可以访问不同分段锁上的桶,提高并发性,并发度就是Segment的数量。

反射

首先,什么是反射?说出来你可能不太相信,他强大到可以取到类的私有变量。Java的反射机制是在运行状态中,对于任意的一个类都能知道这个类的所有属性和方法,对于任意一个对象,都能够调用他的任意一个方法和属性,这种动态的获取信息以及动态的调用对象方法的功能称为Java语言的反射机制。

简单来说,反射就是把Java类中的各种成分映射成一个个Java对象。

等学完类的加载机制再回来看这一块把。

(更新于2021-9-2)

Java的反射机制就是在运行状态中,对于任意一个类,都可以获取它的所有的属性和方法,对于任意一个对象,都能够任意调用它的一个方法和属性.

类加载:

每个类都有一个class对象,包含了与类有关的信息。当编译一个新类时,会产生一个同名的.class文件,该文件内容保存着class对象。

类加载相当于class对象的加载,类在第一次使用时才动态加载到JVM中(这种在需要的时候才加载被称为懒加载机制,相对的,一开始就被加载的机制被称为饿汉式加载机制),也可以使用Class.forName(“com.mysql.jdbc.driver”)这种方式来控制类的加载,该方法会返回一个class对象。

反射可以提供运行时类的信息,并且这个类可以在运行时才加载进来,甚至在编译时期该类的.class不存在也可以加载进来。

参照:www.sczyh30.com/posts/Java/…

这个章节本人并不是很明白,还是上面那句话,等搞清楚类的加载机制再回来看一定是另外一番感受。

异常

你以为Exception是所有异常类的父类?不不不,我上次使用的时候发现Throwable才是(不算object类)。

因为异常还包括Error,所以Throwable包括Error和Exception,其中error用来处理JVM无法解决的错误。

Exception又分为两种异常:

  • 受检异常:使用try…catch…语句可以捕获异常并使程序继续运行(即使程序从异常中恢复,不会中断程序)。
  • 非受检异常:是程序运行时出错,此时程序崩溃且无法回复(程序抛出异常并中断)。例如除数为0会引发Arithmetic Exception,此时程序会直接退出。

image-20210717210832169

异常其实本身不是很重要,但是学会处理异常很重要。

数组下标越界

内存溢出

文件未找到

泛型

啊,泛型啊,蛮常见的还算,例如ArrayList,通常使用T来声明。

/**
 * @author masuo
 * @create 2021/7/17 21:36
 * @Description 泛型
 */
public class Genericity {
    public static void main(String[] args) {
        genericity();
    }

    private static void genericity() {
        class Box<T>{
            private T t;
            public Box(T t){
                this.t = t;
            }

            public Class<?> getClassName(){
                return t.getClass();
            }
        }

        Box<String> b1 = new Box<>("ss");
        Box<Integer> b2 = new Box<>(111);
        System.out.println(b1.getClassName());
        System.out.println(b2.getClassName());
    }
}