String类中常用方法源码解析

初学String的时候完全不知道String里面有一大堆处理字符串的方法,硬是傻乎乎地自己去写,但是自从知道这些方法并且用了这么长时间一直咩有研究人家的具体实现,实在是丢人!学习人家的思路,帮助自己成长,本着这个目的开始了我的本篇博客

M1 length( )和 isEmpty( )

public int length() {
     return count;
}

public boolean isEmpty() {
      return count == 0;
}

M2 equals( )

public boolean equals(Object anObject) {
        if (this == anObject) {//同一个对象就直接返回true
            return true;
        }
        if (anObject instanceof String) {//"abc"和"ab"比较
            String anotherString = (String) anObject;
            int n = count;
            if (n == anotherString.count) {//.count是系统方法,编译器可以通过
                int i = 0;
                while (n-- != 0) {
                    if (charAt(i) != anotherString.charAt(i))
                            return false;
                    i++;
                }
                return true;
            }
        }
        return false;
    }

M3 startsWith()

public boolean startsWith(String prefix, int toffset) {
        int to = toffset;
        int po = 0;
        int pc = prefix.count;
        // Note: toffset might be near -1>>>1.
        if ((toffset < 0) || (toffset > count - pc)) {
            return false;
        }
        while (--pc >= 0) {
            if (charAt(to++) != prefix.charAt(po++)) {
                return false;
            }
        }
        return true;
    }

 public boolean startsWith(String prefix) {
        return startsWith(prefix, 0);//如果没有写int默认是0
    }

po是子串的初始位置,to是原串的偏移位置,偏移量与子串长度之和不能大于原串长度

M4 endsWith()

  public boolean endsWith(String suffix) {
       return startsWith(suffix, count - suffix.count);
  }

M5 charAt(int index)

 public native char charAt(int index);//这个方法需要底层编写
 这个方法的特殊之处在于他的返回值,可以是char单字符,也可以是unicode码整数

这里写图片描述

M6 hashCode()

 /** Cache the hash code for the string */
    private int hash; // Default to 0  

public int hashCode() {
        int h = hash;
        if (h == 0 && count > 0) {
            for (int i = 0; i < count; i++) {
                h = 31 * h + charAt(i);
            }
            hash = h;
        }
        return h;
    }

哈希值用来唯一标识每个字符串,默认hash为0,如果字符串为空串,那么就返回0,如果不为空,就按照s[0]*31^(n-1) + s[1]*31^(n-2) + … + s[n-1]计算哈希值

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值