您的位置:首页 > 编程语言 > Java开发

String类源码分析(JDK1.7)

2016-07-17 14:26 896 查看
以下学习根据JDK1.7String类源代码做注释

publicfinalclassString
implementsjava.io.Serializable,Comparable<String>,CharSequence{
//String类是final的,也就是说String类不允许被继承,实现了Serializable接口(可以序列化和反序列化),Comparale(可以进行自定义的字符串比较)
CharSequence(一个可读序列。此接口对许多不同种类的char序列提供统一的只读访问。StringBuilder和StringBuffer也实现了这个接口)


privatefinalcharvalue[];//用于存放string字符的数组
privateinthash;//表示string字符的哈希值,默认为0






//默认构造方法,一般不用,因为String字符串是不可改变的
publicString(){
this.value=newchar[0];
}
//有参构造方法,使用已存在的一个字符串创建一个相同字符序列的字符串
publicString(Stringoriginal){
this.value=original.value;
this.hash=original.hash;
}
//使用一个字符数组创建一个字符串
publicString(charvalue[]){
this.value=Arrays.copyOf(value,value.length);
//使用Arrays类复制字符数组并赋值给String类声明的value
}

//使用字符数组的一部分创建一个字符串对象offset字符数组开始位置,count数组开始位置往后的长度
publicString(charvalue[],intoffset,intcount){
if(offset<0){
thrownewStringIndexOutOfBoundsException(offset);
}
if(count<0){
thrownewStringIndexOutOfBoundsException(count);
}
//Note:offsetorcountmightbenear-1>>>1.
if(offset>value.length-count){
thrownewStringIndexOutOfBoundsException(offset+count);
}
this.value=Arrays.copyOfRange(value,offset,offset+count);
}




//将字节数组从offset开始,长度为length并以chatsetName编码转换成字符串
publicString(bytebytes[],intoffset,intlength,StringcharsetName)
throwsUnsupportedEncodingException{
if(charsetName==null)
thrownewNullPointerException("charsetName");
checkBounds(bytes,offset,length);
this.value=StringCoding.decode(charsetName,bytes,offset,length);
}


//返回字符串的长度
publicintlength(){
returnvalue.length;
}
//判断字符串长度是否为0
publicbooleanisEmpty{
retutnvalue.length==0

}
//根据下标获取字符
publiccharcharAt(intindex){
if((index<0)||(index>=value.length)){
thrownewStringIndexOutOfBoundsException(index);
}
returnvalue[index];
}

//equals比较的是值
publicbooleanequals(ObjectanObject){
if(this==anObject){//如果是同一个对象,返回true
returntrue;
}
if(anObjectinstanceofString){//判断是否是string对象
StringanotherString=(String)anObject;
intn=value.length;
if(n==anotherString.value.length){//判断长度是否一致
charv1[]=value;
charv2[]=anotherString.value;
inti=0;
while(n--!=0){
if(v1[i]!=v2[i])//比较每个字符是否一样
returnfalse;
i++;
}
returntrue;
}
}
returnfalse;
}


//采用乘法hash算法,字符串相同hash值一定相同,hash值相同,不一定字符串相同
publicinthashCode(){
inth=hash;
if(h==0&&value.length>0){
charval[]=value;

for(inti=0;i<value.length;i++){
h=31*h+val[i];每一次的hash值乘31+该字符
}
hash=h;
}
returnh;
}




                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: