jdk1.8 String 源码解析
一、String类
public final class String
implements java.io.Serializable, Comparable<String>, CharSequence {
//用于存储字符的字符数组,值不可更改
private final char value[];
//该字符串的hash code,默认值为0
private int hash; // Default to 0
从上面可以看出:
1)String类被final修饰,说明该类不能被继承
2)String类是用数据结构字符数组存储的数据,其中该数组用final修饰,说明该数组变量就变成了常量,只能被赋值一次。另外用final修饰的方法不能被重写
1.用到的构造函数:
//返回一个新的字符串,其中以指定位置offset的字符开始,长度为count
public String(char value[], int offset, int count) {
if (offset < 0) {
throw new StringIndexOutOfBoundsException(offset);
}
if (count <= 0) {
if (count < 0) {
throw new StringIndexOutOfBoundsException(count);
}
if (offset <= value.length) {//count为0
this.value = "".value;
return;
}
}
// Note: offset or count might be near -1>>>1.
if (offset > value.length - count) {
throw new StringIndexOutOfBoundsException(offset + count);
}
//把一个新的字符数组(以指定位置offset开始,以offset+count结尾)赋值给新的字符串的value属性,
this.value = Arrays.copyOfRange(value, offset, offset+count);
}
二、一些常用的方法
1.trim()方法:过滤头部和尾部的空格
//返回一个头部和尾部的空格被去掉的String
public String trim() {
int len = value.length;
int st = 0;
char[] val = value; /* avoid getfield opcode */
while ((st < len) && (val[st] <= ' ')) {//执行完该循环,st指向从头开始该String的第一个不是空格的字符
st++;
}
while ((st < len) && (val[len - 1] <= ' ')) {//执行完该循环,st指向从尾开始该String的第一个不是空格的字符
len--;
}
return ((st > 0) || (len < value.length)) ? substring(st, len) : this;
}
注意
之所以判断头部或尾部的字符是否是空格,用了<= ' ',而不是== ' '。是因为空格的ascii码值为32,而ascii码值为0-31是控制字符属于不可见字符
2.String substring(int beginIndex)
//返回一个子串,该子串以特定位置的字符为开始,直到原字符串的结尾
public String substring(int beginIndex) {
if (beginIndex < 0) {
throw new StringIndexOutOfBoundsException(beginIndex);
}
int subLen = value.length - beginIndex;//子串的长度
if (subLen < 0) {
throw new StringIndexOutOfBoundsException(subLen);
}
return (beginIndex == 0) ? this : new String(value, beginIndex, subLen);
}
3.String substring(int beginIndex, int endIndex)
//返回一个原字符串的子串,以指定位置beginIndex的字符开始,以指定位置endIndex-1的字符结尾,长度为endIndex - beginIndex
public String substring(int beginIndex, int endIndex) {
if (beginIndex < 0) {
throw new StringIndexOutOfBoundsException(beginIndex);
}
if (endIndex > value.length) {
throw new StringIndexOutOfBoundsException(endIndex);
}
int subLen = endIndex - beginIndex;
if (subLen < 0) {
throw new StringIndexOutOfBoundsException(subLen);
}
return ((beginIndex == 0) && (endIndex == value.length)) ? this
: new String(value, beginIndex, subLen);
}
三、应用
public class TestString {
public static void main(String args[]){
char whiteChar = ' ';
int acsii = whiteChar;
System.out.println("空格的acsii值为"+acsii);
String s = "abcdefg";
String subStr1 = s.substring(2);
String subStr2 = s.substring(2,5);
System.out.println("subStr1="+subStr1);
System.out.println("subStr2="+subStr2);
}
}
运行结果: