HashMap源码解读

源码是基于JDK1.7的

类图

StringBuilder.png

构造方法

  • 构造默认容量为16个字符的数组大小
    Package construct.png

追加操作

追加操作.jpg

追加实现

  • 追加实现默认调用父类方法
  • 针对追加对象的不同有不同的实现方法和实现逻辑
    追加案例.jpg

扩容操作

  • 在进行追加之前需要保障字符数组足够长
    扩容操作.jpg

插入操作

  • 插入不等同于追加
  • 插入需要先进行入参判断
  • 为了保障高效插入使用jni方法进行数组复制(system.arraycopy)
    插入操作实现.jpg

字符拷贝.jpg

字符串查找

字符串查找.jpg

 /**
     * Code shared by String and StringBuffer to do searches. The
     * source is the character array being searched, and the target
     * is the string being searched for.
     *
     * @param   source       被搜索的原字符串
     * @param   sourceOffset 原字符串搜索的偏移量(就是从第几位索引位置开始搜索)这里传入的是0
     * @param   sourceCount  原字符串的字符数组长度
     * @param   target       搜索的目标字符串
     * @param   targetOffset 搜索的目标字符串的偏移量(就是从第几位索引位置开始搜索) 这里传入的是0
     * @param   targetCount  目标字符串的字符数组长度 
     * @param   fromIndex    指定从第几位索引位置开始搜索
     */
    static int lastIndexOf(char[] source, int sourceOffset, int sourceCount,
            char[] target, int targetOffset, int targetCount,
            int fromIndex) {
        /*
         * 
         * 首先检查参数,不进行空校验,因为假定入参不是空,如果没有则尽快返回。
         */
        //找到搜索的最后位置
        int rightIndex = sourceCount - targetCount;
        //索引位置为负,则直接返回找不到
        if (fromIndex < 0) {
            return -1;
        }
       //索引位置超过搜索的最后位置,则以最后位置为准
        if (fromIndex > rightIndex) {
            fromIndex = rightIndex;
        }
        //如果目标字符串的长度是0,则默认是匹配成功的,进行返回
        if (targetCount == 0) {
            return fromIndex;
        }
       //根据目标字符串的偏移量和目标字符串的大小找到最后匹配字符串的索引下标
        int strLastIndex = targetOffset   targetCount - 1;
       //找到需要匹配的第一个字符串
        char strLastChar = target[strLastIndex];
       //计算原字符串需要搜索的起始位置
        int min = sourceOffset   targetCount - 1;
       //计算原字符串需要搜索的结束位置
        int i = min   fromIndex;

       //根据下标循环匹配直到找到或者找不到
        startSearchForLastChar:
        while (true) {
            while (i >= min && source[i] != strLastChar) {
                i--;
            }
            if (i < min) {
                return -1;
            }
            int j = i - 1;
            int start = j - (targetCount - 1);
            int k = strLastIndex - 1;

            while (j > start) {
                if (source[j--] != target[k--]) {
                    i--;
                    continue startSearchForLastChar;
                }
            }
            //计算找到后的下标
            return start - sourceOffset   1;
        }
    }

序列化与toString

字符可读.jpg

架构设计@工程设计@服务稳定性之路

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值