java.lang中String类源码分析

一、类
public final class String:final关键字说明String类不能被修改(不能被其他类继承和重写)

public final class String
    implements java.io.Serializable, Comparable<String>, CharSequence

二、方法
1、subString(int beginIndex, int endIndex):截取子字符串
1) 第一层方法

public String substring(int beginIndex, int endIndex) {
        // beginIndex校验不能小于0
        if (beginIndex < 0) {
            throw new StringIndexOutOfBoundsException(beginIndex);
        }
        // endIndex校验不能>数组长度
        if (endIndex > value.length) {
            throw new StringIndexOutOfBoundsException(endIndex);
        }
        // 获取要截取的子字符串的长度
        int subLen = endIndex - beginIndex;
        if (subLen < 0) {
            throw new StringIndexOutOfBoundsException(subLen);
        }
        // 判断
        return ((beginIndex == 0) && (endIndex == value.length)) ? this
                : new String(value, beginIndex, subLen);
    }

2) 调用String的有参构造方法

public String(char value[], int offset, int count) {
		// beginIndex不能小于0
        if (offset < 0) {
            throw new StringIndexOutOfBoundsException(offset);
        }
        // count = endIndex-beginIndex <=0的情况
        if (count <= 0) {
        	// count小于0,抛出异常
            if (count < 0) {
                throw new StringIndexOutOfBoundsException(count);
            }
            // count = 0时,输出空字符串
            if (offset <= value.length) {
                this.value = "".value;
                return;
            }
        }
        // endIndex > value.length长度时抛出异常
        if (offset > value.length - count) {
            throw new StringIndexOutOfBoundsException(offset + count);
        }
        // 执行数组复制
        this.value = Arrays.copyOfRange(value, offset, offset+count);
    }

3) 调用Arrays.copyOfRange方法实现复制数组中元素到另外一个char数组中

public static char[] copyOfRange(char[] original, int from, int to) {
        int newLength = to - from;
        if (newLength < 0)
            throw new IllegalArgumentException(from + " > " + to);
        // 声明一个char数组,用来装载截取的子字符串
        char[] copy = new char[newLength];
        // 核心代码,最终通过它实现将char原始数组中的元素复制到另外一个char数组中
        System.arraycopy(original, from, copy, 0,
                         Math.min(original.length - from, newLength));
        return copy;
    }

未完待续~

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值