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; }
相关文章推荐
- java设计模式-工厂模式
- java文件及读写操作
- SSM框架整合(IntelliJ IDEA + maven + Spring + SpringMVC + MyBatis)
- 开源java数据库库
- Servlet的生命周期
- 《java虚拟机》汇总所有关键要点
- java设计模式之单例模式
- 关于java中的编码问题
- JAVA——设计模式
- 使用spring的aop模拟事物
- springmvc(18)使用WebSocket 和 STOMP 实现消息功能
- Java GZip数据压缩传输到前台
- WebService学习总结九 使用Spring发布WebService
- struts2的jsp页面下载文件
- Java网页爬虫utf-8
- 【问题-java-json】josn的发送与接收(全)解析json对象与字符串在js中的区别,以及后端spring该如何接收?
- java多线程版生产者消费者模型
- Java内存模型
- 【Java】Java中关于HashMap的使用和遍历
- eclipse中关于复制和移动一行代码的快捷键