您的位置:首页 > 其它

String类中常用方法源码解析

2017-10-11 21:54 471 查看
初学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]计算哈希值
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  string 源码