java String源码阅读2

compareTo(StringanotherString)compareToIgnoreCase(Stringstr)进行阅读。


public int compareTo(String anotherString) {
int len1 = count;
int len2 = anotherString.count;
int n = Math.min(len1,len2);
char v1[] = value;
char v2[] = anotherString.value;
int i = offset;
int j = anotherString.offset;

if(i == j) {
intk = i;
intlim = n + i;
while(k < lim) {
charc1 = v1[k];
charc2 = v2[k];
if(c1 != c2) {
returnc1 - c2;
}
k++;
}
}else{
while(n-- != 0) {
charc1 = v1[i++];
charc2 = v2[j++];
if(c1 != c2) {
returnc1 - c2;
}
}
}
returnlen1 - len2;
}



分两种情况i==ji!=j。认为只用else部分的代码就能够判断字符串的大小。i++先使用i再加。


compareToIgnoreCase(Stringstr)

内部实现:

public int compareToIgnoreCase(String str) {

       returnCASE_INSENSITIVE_ORDER.compare(this,str);

}

CASE_INSENSITIVE_ORDER是一个静态类,此类实现了Comparable<String>接口:

publicstaticfinalComparator<String> CASE_INSENSITIVE_ORDER

=newCaseInsensitiveComparator();

private static class CaseInsensitiveComparator

implements Comparator<String>, java.io.Serializable {

//use serialVersionUID from JDK 1.2.2 for interoperability

private static final long serialVersionUID= 8575799808933029326L;


public int compare(String s1, String s2) {

int n1=s1.length(), n2=s2.length();

for(inti1=0, i2=0; i1<n1 && i2<n2; i1++, i2++) {

char c1 = s1.charAt(i1);

char c2 = s2.charAt(i2);

if(c1 != c2) {

c1 =Character.toUpperCase(c1);

c2 =Character.toUpperCase(c2);

if(c1 != c2) {

c1= Character.toLowerCase(c1);

c2= Character.toLowerCase(c2);

if(c1 != c2) {

return c1 - c2;

}

}

}

}

return n1 - n2;

}

}

通过charAt()函数获取,字符串中的每个字符。进行比较,在compareTo中也可以通过此种方式实现。总之这两个函数的实现难度不打。compareTo是直接使用value数组,而compareToIgnoreCase()使用了String类中的charAt函数。

其中++和—的使用和字符大小的比较是值得学习的。



concat(Stirngstr)函数,对字符串连接。Strings = "string";s是“string”的引用

s.concat("concat");方法调用后s是另一个字符串(”stringconcat”)的引用。具体实现:

public String concat(String str) {

int otherLen = str.length();

if(otherLen == 0) {

return this;

}

charbuf[] = newchar[count+ otherLen];

getChars(0,count, buf,0);

str.getChars(0,otherLen, buf, count);

return new String(0, count+ otherLen, buf);

}

方法中使用一个charbuf用来存储,新的字符串中的字符。ReturnnewString(0, count+ otherLen, buf);返回一个新生成的字符串。GetChars中使用ArrayCopy实现。




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值