String源码笔记

String类的定义:

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

可以看到String类被final修饰,因此不能被继承。String类还实现了序列化接口Serializable、可比较的接口Comparable并指定范型为String,该接口必须要实现int compareTo(T o) 方法。最后还实现了字符序列CharSequence接口,该接口也有些常用的方法,如charAt(int index)
、length()、toString() 等

String类放的无参构造函数

 public String() {
            this.value = "".value;
        }

其中value定义:

 private final char value[];

该构造函数创建了一个空的字符串并存在字符数组value中;

String有参的构造函数:

public String(char value[]) {
        this.value = Arrays.copyOf(value, value.length);
    }

该构造函数指定一个字符数组来创建一个字符序列。是通过Arrays的copyOf方法将字符数组拷贝到当前数组;
这样当修改字符数组的子串时,不会影响新字符数组;
经过以上分析可以看出,下面两个语句是等价的,因为String类底层使用char[]数组来存储字符序列:

char date []= {'a','b','c'}
String str = new String(data);

String的charAt方法:

 public char charAt(int index) {
        if ((index < 0) || (index >= value.length)) {
            throw new StringIndexOutOfBoundsException(index);
        }
        return value[index];
    }

该方法返回字符序列中下标为index的字符。并且index的范围:(0,value.length].

String的contains方法

 public boolean contains(CharSequence s) {
        return indexOf(s.toString()) > -1;
    }

直接调用了indexOf(String str)方法:

public int indexOf(String str) {
        return indexOf(str, 0);
    }

又调用了 indexOf(str, int)方法:

  public int indexOf(String str, int fromIndex) {
        return indexOf(value, 0, value.length,
                str.value, 0, str.value.length, fromIndex);
    }

该方法又返回了以下静态方法:

static int indexOf(char[] source, int sourceOffset, int sourceCount,
            char[] target, int targetOffset, int targetCount,
            int fromIndex) {
        if (fromIndex >= sourceCount) {
            return (targetCount == 0 ? sourceCount : -1);
        }
        if (fromIndex < 0) {
            fromIndex = 0;
        }
        if (targetCount == 0) {
            return fromIndex;
        }

        char first = target[targetOffset];
        int max = sourceOffset + (sourceCount - targetCount);

        for (int i = sourceOffset + fromIndex; i <= max; i++) {
            /* Look for first character. */
            if (source[i] != first) {
                while (++i <= max && source[i] != first);
            }

            /* Found first character, now look at the rest of v2 */
            if (i <= max) {
                int j = i + 1;
                int end = j + targetCount - 1;
                for (int k = targetOffset + 1; j < end && source[j]
                        == target[k]; j++, k++);

                if (j == end) {
                    /* Found whole string. */
                    return i - sourceOffset;
                }
            }
        }
        return -1;
    }

首先判断开始索引如果大于源字符串则返回,若目标字符串长度为0返回源字符串长度,否则返回-1;

然后迭代查找字符,若全部源字符串都找到则返回第一个匹配的索引,否则返回-1;

所以在public boolean contains(CharSequence s)方法中,若indexOf方法返回-1则返回false,否则返回true;

String的equals()方法:

public boolean equals(Object anObject) {
        if (this == anObject) {
            return true;
        }
        if (anObject instanceof String) {
            String anotherString = (String)anObject;
            int n = value.length;
            if (n == anotherString.value.length) {
                char v1[] = value;
                char v2[] = anotherString.value;
                int i = 0;
                while (n-- != 0) {
                    if (v1[i] != v2[i])
                        return false;
                    i++;
                }
                return true;
            }
        }
        return false;
    }

该方法首先判断this == anObject ?,也就是说判断要比较的对象和当前对象是不是同一个对象,如果是直接返回true,如不是再继续比较,然后在判断anObject是不是String类型的,如果不是,直接返回false,如果是再继续比较,到了能终于比较字符数组的时候,他还是先比较了两个数组的长度,不一样直接返回false,一样再逐一比较值

hashCode()方法算法分析

/** The value is used for character storage. */  
private final char value[];  //将字符串截成的字符数组  
  
/** Cache the hash code for the string */  
private int hash; // Default to 0 用以缓存计算出的hashcode值  
  /**
     * Returns a hash code for this string. The hash code for a
     * {@code String} object is computed as
     * <blockquote><pre>
     * s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
     * </pre></blockquote>
     * using {@code int} arithmetic, where {@code s[i]} is the
     * <i>i</i>th character of the string, {@code n} is the length of
     * the string, and {@code ^} indicates exponentiation.
     * (The hash value of the empty string is zero.)
     *
     * @return  a hash code value for this object.
     */
    public int hashCode() {
        int h = hash;
        if (h == 0 && value.length > 0) {
            char val[] = value;

            for (int i = 0; i < value.length; i++) {
                h = 31 * h + val[i];
            }
            hash = h;
        }
        return h;
    }

按照上面源码举例说明:

String X = “abcd”; // 此时value[] = {‘a’,‘b’,‘c’,‘d’} 因此

for循环会执行4次

第一次:h = 31*0 + a = 97

第二次:h = 31*97 + b = 3105

第三次:h = 31*3105 + c = 96354

第四次:h = 31*96354 + d = 2987074

由以上代码计算可以算出 X的hashcode = 2987074 刚好与 System.err.println(new String("abcd").hashCode()); 相等

在源码的hashcode的注释中还提供了一个多项式计算方式:

s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]      

s[0] :表示字符串中指定下标的字符

n:表示字符串中字符长度

a*31^3 + b*31^2 + c*31^1 + d = 2987074  + 94178 + 3069 + 100 = 2987074 ;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值