String
String类在整个JAVA开发中大量运用,在面试时我们也经常会?问到String、StringBuffer和StringBuilder之间的区别。虽然我们可以通过阅读现有的面经获得这些区别,但是终究没有亲眼见过,而阅读String源码能够使我们更好的了解它。
String不可继承
public final class String implements java.io.Serializable, Comparable<String>, CharSequence {
//其他代码
}
可以发现String类被final修饰了,这说明String没有子类。同时String实现了Serializable接口,说明它可以序列化,实现Comparable接口用于比较。String 继承于CharSequence,也就是说String也是CharSequence类型。CharSequence是一个接口,它只包括length(), charAt(int index), subSequence(int start, int end)这几个API接口。除了String实现了CharSequence之外,StringBuffer和StringBuilder也实现了CharSequence接口。需要说明的是,CharSequence就是字符序列,String, StringBuilder和StringBuffer本质上都是通过字符数组实现的!
String的主要属性
/** The value is used for character storage. */
private final char value[];
/** Cache the hash code for the string */
private int hash; // Default to 0
通过上面我们可以了解以下信息:
- String是使用char[]实现的,由于final的修饰,说明String的值是不可变的;
- String的默认hash码是0。
String构造方法
public String() {
this.value = "".value;
}
这个构造方法创建一个空的字符串。
public String(String original) {
this.value = original.value;
this.hash = original.hash;
}
使用另一个字符串(original)构造,创建的字符串拥有original串的value和hash码。
String str1 = "This is String";
String str2 = new String(str1);
System.out.println(str1.hashCode());//1090680069
System.out.println(str2.hashCode());//1090680069
System.out.println(str1.equals(str2));//比较值:true
System.out.println(str1==str2);//比较内存地址:false
public String(char value[]) {
this.value = Arrays.copyOf(value, value.length);
}
使用一个字符数组创建字符串,可以发现是使用Arrays.copyOf()函数将value中的字符复制到一个新字符数组赋值给创建的字符串的value属性。
char chs[] = {'a','b','c','d','e'};
String str = new String(chs);
System.out.println(str);//abcde
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) {
this.value = "".value;
return;
}
}
// Note: offset or count might be near -1>>>1.
if (offset > value.length - count) {
throw new StringIndexOutOfBoundsException(offset + count);
}
this.value = Arrays.copyOfRange(value, offset, offset+count);
}
同样是使用字符数组创建字符串,不过和上面不同的是我们可以选择字符数组的部分字符来创建字符串。offset为偏移量,count为选取字符的个数。同时我们需要注意的是不能越界,否则会抛出StringIndexOutOfBoundsException异常。
public String(int[] codePoints, int offset, int count) {
if (offset < 0) {
throw new StringIndexOutOfBoundsException(offset);
}
if (count <= 0) {
if (count < 0) {
throw new StringIndexOutOfBoundsException(count);
}
if (offset <= codePoints.length) {
this.value = "".value;
return;
}
}
// Note: offset or count might be near -1>>>1.
if (offset > codePoints.length - count) {
throw new StringIndexOutOfBoundsException(offset + count);
}
final int end = offset + count;
// Pass 1: Compute precise size of char[]
int n = count;
for (int i = offset; i < end; i++) {
int c = codePoints[i];
if (Character.isBmpCodePoint(c))
continue;
else if (Character.isValidCodePoint(c))
n++;
else throw new IllegalArgumentException(Integer.toString(c));
}
// Pass 2: Allocate and fill in char[]
final char[] v = new char[n];
for (int i = offset, j = 0; i < end; i++, j++) {
int c = codePoints[i];
if (Character.isBmpCodePoint(c))
v[j] = (char)c;
else
Character.toSurrogates(c, v, j++);
}
this.value = v;
}
在unicode的世界中,每种字符都有一个唯一的数字编号,这个数字编号就叫unicode code point。我们可以不使用字符数组创建字符串,可以传递字符的unicode编码。除了需要注意越界之外我们还需要判断int数组中的值是否是在正确的unicode范围内,再进行字符的填充。
int[] codePoints = {97,98,99,100,101,102};
String str = new String(codePoints,1,5);
System.out.println(str);//bcdef
int[] codePoints2 = {97,1114112,99,100,101,102};
String str2 = new String(codePoints2,1,5);
System.out.println(str2);
/*int数组中的值超出了范围(最大1114111,最小0)
Exception in thread "main" java.lang.IllegalArgumentException: 1114112
at java.lang.String.<init>(String.java:266)
at StringTest.main(StringTest.java:21)
*/
String(byte bytes[]) String(byte bytes[], int offset, int length)
String(byte bytes[], Charset charset)
String(byte bytes[], String charsetName)
String(byte bytes[], int offset, int length, Charset charset)
String(byte bytes[], int offset, int length, String charsetName)
使用byte[]构造String,我们需要制定charset或charsetName(编码),底层使用StringCoding.decode()
进行解码,如果我们不指定编码,那么java使用默认的ISO-8859-1进行解码。
public String(StringBuffer buffer) {
synchronized(buffer) {
this.value = Arrays.copyOf(buffer.getValue(), buffer.length());
}
}
public String(StringBuilder builder) {
this.value = Arrays.copyOf(builder.getValue(), builder.length());
}
使用StringBuffer和StringBuilder构造字符串,我们可以发现前者是个线程安全的方法。实际上我们可以使用StringBuffer或StringBuilder的toString方法获取字符串。
getChars()
public void getChars(int srcBegin, int srcEnd, char dst[], int dstBegin) {
if (srcBegin < 0) {
throw new StringIndexOutOfBoundsException(srcBegin);
}
if (srcEnd > value.length) {
throw new StringIndexOutOfBoundsException(srcEnd);
}
if (srcBegin > srcEnd) {
throw new StringIndexOutOfBoundsException(srcEnd - srcBegin);
}
System.arraycopy(value, srcBegin, dst, dstBegin, srcEnd - srcBegin);
}
将字符串中的部分字符拷贝到目标字符数组中。System.arraycopy()方法是个native方法,它通过手工编写汇编或其他优化方法来进行 Java 数组拷贝,这种方式比起直接在 Java 上进行 for 循环或 clone 是更加高效的。数组越大体现地越明显。
equals()
public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
String anotherString = (String)anObject;
int n = value.length;
if (n == anotherString.value.length) {
char v1[] = value;
char v2[] = anotherString.value;
int i = 0;
while (n-- != 0) {
if (v1[i] != v2[i])
return false;
i++;
}
return true;
}
}
return false;
}
在Object类中equals方法比较的是内存地址,String类对此方法进行了重写,首先比较内存地址,相同自然相等,否则判断传递过来的对象是不是字符串,如果是则逐一比较每个字符是否相同,一旦发现不同则返回false,全部比较完返回true,否则直接返回false。还有一个与之类似的方法equalsIgnoreCase,它忽略大小写进行比较。
hashCode()
public int hashCode() {
int h = hash;
if (h == 0 && value.length > 0) {
char val[] = value;
for (int i = 0; i < value.length; i++) {
h = 31 * h + val[i];
}
hash = h;
}
return h;
}
String默认的hash值为0,空串的hash值为0。通过阅读源码我们可了解hash值的产生方法:s[0]*31^(n-1) + s1*31^(n-2) + … + s[n-1],s[n]表示字符串中的字符。这里也引出一个算法Rabin-Karp算法,它可高效的实现strstr(查找子串索引)方法。还有一点,为什么是乘以31呢?这个问题自行查阅资料。
compareTo()
public int compareTo(String anotherString) {
int len1 = value.length;
int len2 = anotherString.value.length;
int lim = Math.min(len1, len2);
char v1[] = value;
char v2[] = anotherString.value;
int k = 0;
while (k < lim) {
char c1 = v1[k];
char c2 = v2[k];
if (c1 != c2) {
return c1 - c2;
}
k++;
}
return len1 - len2;
}
通过以上代码我们可以知道,如果两个字符串相同,返回0;如果两个字符串不同,返回不同字符之间的差值。与之类似的还有compareToIgnoreCase,它忽略大小写比较。
startsWith()
public boolean startsWith(String prefix, int toffset) {
char ta[] = value;
int to = toffset;
char pa[] = prefix.value;
int po = 0;
int pc = prefix.value.length;
// Note: toffset might be near -1>>>1.
if ((toffset < 0) || (toffset > value.length - pc)) {
return false;
}
while (--pc >= 0) {
if (ta[to++] != pa[po++]) {
return false;
}
}
return true;
}
判断字符串在偏移位置是否是以prefix开始的。如果判断字符串是否已prefix开始的可以直接使用startsWith(String prefix)方法。
JAVA还有个endsWith(String?surfix)方法,判断是否以surfix结尾。它的实现还是依托以startsWith方法:
public boolean endsWith(String suffix) {
return startsWith(suffix, value.length - suffix.value.length);
}
indexOf()
public int indexOf(int ch, int fromIndex) {
final int max = value.length;
if (fromIndex < 0) {
fromIndex = 0;
} else if (fromIndex >= max) {
// Note: fromIndex might be near -1>>>1.
return -1;
}
if (ch < Character.MIN_SUPPLEMENTARY_CODE_POINT) {
// handle most cases here (ch is a BMP code point or a
// negative value (invalid code point))
final char[] value = this.value;
for (int i = fromIndex; i < max; i++) {
if (value[i] == ch) {
return i;
}
}
return -1;
} else {
return indexOfSupplementary(ch, fromIndex);
}
}
此方法从fromIndex开始查找获取字符ch第一次出现的位置索引。如果从字符串开头查找则可以使用index(int ch)方法,底层是fromIndex=0。除了寻找字符的第一次出现的索引位置,indexOf()重载了查找String第一次出现索引的位置。同时,indexOf是从左至右查找,存在lastIndexOf()从右至左查找。
substring(int beginIndex, int endIndex)
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);
}
此方法截取字符串的部分作为子串。可以发现底层使用字符数组部分字符构造字符串。
concat(String str)
public String concat(String str) {
int otherLen = str.length();
if (otherLen == 0) {
return this;
}
int len = value.length;
char buf[] = Arrays.copyOf(value, len + otherLen);
str.getChars(buf, len);
return new String(buf, true);
}
此方法将str字符串连接到当前字符串结尾。底层是实现一个len+otherLen长的字符数组,先将当前字符串拷贝进去,再通过getChars()将str的字符拷贝进去,最后使用构造方法创建一个新串。
replace(char oldchar,char newchar)
public String replace(char oldChar, char newChar) {
if (oldChar != newChar) {//替换字符不变不进行操作,返回this,不会创建对象
int len = value.length;
int i = -1;
char[] val = value; /* avoid getfield opcode */
while (++i < len) {
if (val[i] == oldChar) {//找到第一个要替换的字符的下标
break;
}
}
//字符串内无要替换的字符,则返回this,不会创建新对象
if (i < len) {
char buf[] = new char[len];
for (int j = 0; j < i; j++) {
buf[j] = val[j];//替换字符前的字符复制入新字符数组中
}
//遍历要替换字符首次出现的下标到结尾,替换并复制入新char数组
while (i < len) {
char c = val[i];// 将原char赋值入新数组
buf[i] = (c == oldChar) ? newChar : c;//替换目标字符
i++;
}
return new String(buf, true);
}
}
return this;
}
源码思路是找到第一个出现的oldChar,如果oldChar的下标小于len的下标,把oldChar前面的存到临时变量buf中,把oldChar后面的所有oldChar都变为newChar。
trim()
public String trim() {
int len = value.length;
int st = 0;
char[] val = value; /* avoid getfield opcode */
while ((st < len) && (val[st] <= ' ')) {
st++;
}
while ((st < len) && (val[len - 1] <= ' ')) {
len--;
}
return ((st > 0) || (len < value.length)) ? substring(st, len) : this;
}
这个trim()是去掉首尾的空格,而实现方式也非常简单,分别找到第一个非空格字符的下标,与最后一个非空格字符的下标
然后返回之间的子字符串。首位均未出现空格时返回原字符串对象。
intern()
public native String intern();
这个方法是一个 native 的方法。如果常量池中存在当前字符串, 就会直接返回当前字符串. 如果常量池中没有此字符串, 会将此字符串放入常量池中后, 再返回。
深入理解intern可以查看这篇文章:深入解析String#intern
文章同步至【个人站】