JDK 源码学习之String

来源:互联网 发布:信阳师范学院网络教学 编辑:程序博客网 时间:2024/05/01 13:17

String 源码


    String是一个基础的字符串类 说白了它所接受的参数是由多个字符构成的数组  可以简单的理解为String是一个char[] 数组的表现形式

    String.class 中有一段如下源码:

     public String(String s)
    {
        int i = s.count;
        char ac[] = s.value;
        char ac1[];
        if(ac.length > i)
        {
            int j = s.offset;
            ac1 = Arrays.copyOfRange(ac, j, j + i);
        } else
        {
            ac1 = ac;
        }
        offset = 0;
        count = i;
        value = ac1;
    }


当我们定义一个String s1 = "Abcd"; String s2 = s1.substring(3) s2.value为 "Abc" s2.count=3 s1.length=4 

String s3=new String(s2);


其中 s1的value为"Abcd"的数组,offset为0,coun为4

       b的value为"Abcd"的数组,offset1,count为3


就会出现

if(ac.length > i)
        {
            int j = s.offset;
            ac1 = Arrays.copyOfRange(ac, j, j + i);
        } 

其实这边注意要理解的是s2的value值  s2是从s1截取的前三个字符 但是它所指向的值仍然是s1,即s2.count跟s1的length大小是不相等的


下面是String.subString源码:


 public String substring(int i)
    {
        return substring(i, count);
    }


    public String substring(int i, int j)
    {
        if(i < 0)
            throw new StringIndexOutOfBoundsException(i);
        if(j > count)
            throw new StringIndexOutOfBoundsException(j);
        if(i > j)
            throw new StringIndexOutOfBoundsException(j - i);
        else
            return i != 0 || j != count ? new String(offset + i, j - i, value) : this;
    }





0 0