今天来学习一下String类的源码,首先看一下String类,
public final class String
implements java.io.Serializable, Comparable<String>, CharSequence
从String类的定义我们可以看出,该类是final修饰的不可变的类,它实现了序列化和Comparable及CharSequence接口。
- final修饰的String类,说明String所定义的字符串的值是不可修改的。
String类中的变量
private final char value[];
在String中定义了一个私有的字符数组value,它是final所修饰的,其中字符数组的元素也是不可以修改的,该字符数组的值是字符数组中的字符。
private int hash;
hash变量是一个int型,该变量用来记录字符串的哈希值。
字符数组转字符串的方法
public String(char value[]) {
this.value = Arrays.copyOf(value, value.length);
}
public static char[] copyOf(char[] original, int newLength) {
char[] copy = new char[newLength];
System.arraycopy(original, 0, copy, 0,
Math.min(original.length, newLength));
return copy;
}
该方法是String类的有参构造方法,参数为一个字符数组,内部实现是调用了Arrays类的copyOf方法,第一个参数是字符数组的内容,第二个是字符数组的长度。
public class TestString {
public static void main(String[] args){
String str = "abc";
char[] a = {'a','b','c'};
System.out.print(new String(a,1,2));
}
}
运行结果bc
其中使用了String类的构造方法String(char[] a,int offset,int count)
,该方法返回一个字符数组的子串,a代表字符数组,offset代表要构造的新字符串在字符数组a中的下标,count代表从offset下标开始连续的几个字符来构造子字符串,下面是源代码的实现:
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);
}
调用Arrays类的copyOfRange方法,value就是原字符数组,offset就是新字符串在父字符串中索引,offset+count是那个索引与要截取的字符串的个数的总和。
public static char[] copyOfRange(char[] original, int from, int to) {
int newLength = to - from;
if (newLength < 0)
throw new IllegalArgumentException(from + " > " + to);
char[] copy = new char[newLength];
System.arraycopy(original, from, copy, 0,
Math.min(original.length - from, newLength));
return copy;
}
copyOfRange方法中,首先是计算一下要构造的新字符数组的长度,然后创建一个新的字符数组,接着调用System.arraycopy方法。最后将构造好的子字符串进行返回。
public String(StringBuffer buffer) {
synchronized(buffer) {
this.value = Arrays.copyOf(buffer.getValue(), buffer.length());
}
}
该String类的构造方法的参数是StringBuffer对象,因为StringBuffer类不是线程安全的,所以在调用Arrays.copyof的方法时给buffer对象添加了synchronized关键字来进行线程同步,保证多线程情况下的线程安全性。
public String(StringBuilder builder) {
this.value = Arrays.copyOf(builder.getValue(), builder.length());
}
该String类的构造方法是一个带StringBuilder对象的参数,也是将StringBuilder对象的内容构造为String对象。因为StringBuilder是线程安全的,所以不需要添加synchronized关键字来保证线程同步。
public int length() {
return value.length;
}
length()
方法返回字符串的长度,返回值为int类型。(String对象在非NULL的情况下才可以调用该方法)
public boolean isEmpty() {
return value.length == 0;
}
isEmpty()
方法用来判断字符串是否为空,当且仅当字符串的长度为0时,该方法才返回true。(String对象在非NULL的情况下才可以调用该方法)
public char charAt(int index) {
if ((index < 0) || (index >= value.length)) {
throw new StringIndexOutOfBoundsException(index);
}
return value[index];
}
charAt(int index)
方法,返回值类型为char型,字符,参数为字符串的索引值是int类型,首先会判断参数是否是合法的索引值,如果是合法的索引值,然后返回value[index]
代表了该索引在字符串中对应的字符。
getBytes(String charsetName)
方法的例子:
public class TestString {
public static void main(String[] args){
String str = "张三";
try {
byte[] b = str.getBytes("utf-8");
//通过下面的方法是将上面字节数组的内容还原为字符串
String utf_byte = new String(str.getBytes("utf-8"),"utf-8");
for(byte b1:b){
//将字符串按照utf-8进行转码,返回的字节数组
System.out.print(b1);
}
System.out.println();
System.out.println(utf_byte);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
运行结果:前面是将字符串转为字节数组的内容,后面是将字节数组还原为原来的字符串。
-27-68-96-28-72-119张三
public byte[] getBytes(String charsetName)
throws UnsupportedEncodingException {
if (charsetName == null) throw new NullPointerException();
return StringCoding.encode(charsetName, value, 0, value.length);
}
getBytes(String charsetName)
方法是用来根据指定的字符编码来返回对应的字节数组,其中调用了StringCoding类的encode方法。
static byte[] encode(String charsetName, char[] ca, int off, int len)
throws UnsupportedEncodingException
{
StringEncoder se = deref(encoder);//如果传入的字符集为null则默认使用、、、、ISO-8859-1
String csn = (charsetName == null) ? "ISO-8859-1" : charsetName;
if ((se == null) || !(csn.equals(se.requestedCharsetName())
|| csn.equals(se.charsetName()))) {
se = null;
try {
Charset cs = lookupCharset(csn);
if (cs != null)
se = new StringEncoder(cs, csn);
} catch (IllegalCharsetNameException x) {}
if (se == null)
throw new UnsupportedEncodingException (csn);
set(encoder, se);
}
return se.encode(ca, off, len);
}
lookupCharset(String csn)
该方法用来获取字符集,首先会根据你传入的字符集名称来判断是否支持,支持的情况下,会返回字符集的名称,否则就会报异常。
private static Charset lookupCharset(String csn) {
if (Charset.isSupported(csn)) {
try {
return Charset.forName(csn);
} catch (UnsupportedCharsetException x) {
throw new Error(x);
}
}
return null;
}
前面有篇文章我说了关于Object类中的equals和hashcode方法,自定义的类如果不重写equals和hashcode方法,那么会默认调用根基类Object类中的equals方法和hashcode方法,下面我们阅读一下String类重写Object类的equals方法源码:
public boolean equals(Object anObject) {
if (this == anObject) {//先判断当前引用对象this是否是Object类型
return true;
}//判断当前this对象是否是String类的实例
if (anObject instanceof String) {
String anotherString = (String)anObject;//将Object对象强制转换为String类对象
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;
}
具体如何重写equals和hashcode方法可以参考我的这篇文章:Java重写equals和hashcode方法
接着说一下String
类的对象和StringBuffer
类的对象如何做equals
,可能有人会说,String
和StringBuffer
做equals
时,将StringBuffer
转为String
类型就可以调用equals
,如果你看了StringBuffer
的源码,可以看到该类并没有equals
方法,所以你需要调用StringBuffer
对象的toString()
方法来将其转为String
类型,然后就是两个String
对象之间的equals
调用。
上面是一种方法,我们还可以直接使用String
类自带的contentEquals(StringBuffer sb)
方法来对比,下面我先展示源码,然后在分析源码:
public boolean contentEquals(StringBuffer sb) {
return contentEquals((CharSequence)sb);
}
该方法的参数就是一个StringBuffer的对象,通过比较StringBuffer对象和字符串String的字符序列是否一致,来得到比较结果,当且仅当String对象的字符序列和StringBuffer对象的字符序列一致的情况下才会返回true。其余情况返回false.
我们继续看上面的contentEquals(StringBuffer sb)
的源码,它的返回值是调用了另外一个方法,同名且参数不是同一个类型,属于方法重载,继续展示重载后的方法源码,参数是一个CharSequence对象。
public boolean contentEquals(CharSequence cs) {
// Argument is a StringBuffer, StringBuilder
if (cs instanceof AbstractStringBuilder) {//这个判断不太明白
if (cs instanceof StringBuffer) {//判断是否是StringBuffer对象
synchronized(cs) {//同步CharSequence对象
return nonSyncContentEquals((AbstractStringBuilder)cs);
}
} else {
return nonSyncContentEquals((AbstractStringBuilder)cs);
}
}
// Argument is a String
if (cs instanceof String) {
return equals(cs);
}
// Argument is a generic CharSequence
char v1[] = value;
int n = v1.length;
if (n != cs.length()) {
return false;
}
for (int i = 0; i < n; i++) {//一个字符字符做比较
if (v1[i] != cs.charAt(i)) {
return false;
}
}
return true;
}
AbstractStringBuilder
该类是一个抽象类,JDK1.5引入,实现了接口Appendable, CharSequence
。
不明白的点:
1.AbstractStringBuilder
是一个抽象类,按照道理应该不会有实例,那么怎么会判断CharSequence
对象是否属于AbstractStringBuilder
对象?
public boolean equalsIgnoreCase(String anotherString) {
return (this == anotherString) ? true
: (anotherString != null)
&& (anotherString.value.length == value.length)
&& regionMatches(true, 0, anotherString, 0, value.length);
}
equalsIgnoreCase(String anotherString)
该方法也是比较两个字符串,但是他会忽略字符串的大小写,如果equals,则返回true,否则返回false.
它的实现主要有三个方面;
1.使用==
来比较两个字符串是否相等
2.使用toUpperCase()
方法来全部转为大写比较
3.使用toLowerCase()
方法来全部转为小写比较
其中使用了方法regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len)
来实现2和3的验证,具体实现的源码如下所示:
public boolean regionMatches(boolean ignoreCase, int toffset,
String other, int ooffset, int len) {
char ta[] = value;//原字符串的value
int to = toffset;//原字符串要开始的索引
char pa[] = other.value;//参数字符串的value
int po = ooffset;//参数字符串要开始比较的索引
//边缘校验 Note: toffset, ooffset, or len might be near -1>>>1.
if ((ooffset < 0) || (toffset < 0)
|| (toffset > (long)value.length - len)
|| (ooffset > (long)other.value.length - len)) {
return false;
}
while (len-- > 0) {
char c1 = ta[to++];
char c2 = pa[po++];
if (c1 == c2) {
continue;
}
if (ignoreCase) {
// If characters don't match but case may be ignored,
// try converting both characters to uppercase.
// If the results match, then the comparison scan should
// continue.
char u1 = Character.toUpperCase(c1);
char u2 = Character.toUpperCase(c2);
if (u1 == u2) {
continue;
}
// Unfortunately, conversion to uppercase does not work properly
// for the Georgian alphabet, which has strange rules about case
// conversion. So we need to make one last check before
// exiting.
if (Character.toLowerCase(u1) == Character.toLowerCase(u2)) {
continue;
}
}
return false;
}
return true;
}
regionMatches
方法主要是对比两个字符串是否相等,其中有5个参数,分别是
1.ignoreCase
:如果该值为true,则在比较两个字符串的时候会忽略大小写;
2.toffset
:代表了字符串的起始索引位置;
3.other
:代表了该方法中的参数字符串String;
4.ooffset
:代表参数字符串的起始索引;
5.len
:表示两个字符串要对比的字符个数。
下面看一下String类的compareTo方法:
比较两个字符串中的字符是否一致。它是基于字符串中每个字符的unicode值来做比较的。
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;
}
首先来看一下JDK中compareTo的源码的实现:
1.获取两个字符串的长度;
2.用变量lim来记录两个字符串长度中较小的一个字符串长度值;
3.用两个字符数组v1和v2分别来存储原来两个字符串的内容;
4.定义变量int类型k,初始化为0,并且以k<=lim为循环条件,对两个字符数组中同一索引的字符进行比较,如果不等,则直接return 两个字符的unicode差值 结束循环;此处之所以用两个字符串长度较小的作为最高限,是防止下面两个字符数组访问时出现数组越界的问题;
5.如果while循环顺利通过,compareTo方法最后的返回值是两个字符串长度的差值。
其实我觉得这个实现的话,我觉得应该是这样的:
上述步骤1之后,我们可以比较一下两个字符串的长度,如果当长度不相等的时候,我们就可以直接返回两个长度的差值,我觉得长度都不相等的两个字符串,那么一定是不会equals的。
当两个字符串长度相等的时候再用下面的while循环逐个字符比较unicode值,如果全部相等,则返回两个字符串长度的差值,否则当两个字符的unicode值不相等的时候直接返回该对字符的unicode差值。
下面是几组例子来说明compareTo方法:
public class TestString {
public static void main(String[] args){
String str1 = "abc";
String str2 = "abc";
String str3 = "abe";
String str4 = "abcde";
//结果为0
System.out.println(str1.compareTo(str2));
//结果为-2
System.out.println(str1.compareTo(str3));
//c和e分别对应的数值是12 14
System.out.println(Character.getNumericValue('c') + " " + Character.getNumericValue('e'));
//结果为-2
System.out.println(Character.getNumericValue('c')-Character.getNumericValue('e'));
//结果为-2
System.out.println(str1.compareTo(str4));
}
}
public int compareToIgnoreCase(String str) {
return CASE_INSENSITIVE_ORDER.compare(this, str);
}
compareToIgnoreCase(String str)
该方法参数为String类型,忽略字符串的大小写,返回结果类似于compare的结果,具体的实现是因为调用了toUpperCase和toLowerCase
两个方法。具体可以看源码的实现。
public boolean regionMatches(int toffset, String other, int ooffset,
int len) {
char ta[] = value;
int to = toffset;
char pa[] = other.value;
int po = ooffset;
// Note: toffset, ooffset, or len might be near -1>>>1.
if ((ooffset < 0) || (toffset < 0)
|| (toffset > (long)value.length - len)
|| (ooffset > (long)other.value.length - len)) {
return false;
}
while (len-- > 0) {
if (ta[to++] != pa[po++]) {
return false;
}
}
return true;
}
regionMatches(int toffset, String other, int ooffset, int len)
该方法是用来比较两个字符串是否相等,下面对于方法参数进行一下说明:
1.toffset
:表示当前对象的开始索引;
2.other
:表示方法参数里面的String字符串;
3.ooffset
:表示参数String字符串要开始的索引;
4.len
:表示两个字符串要比较的字符个数。
原理也是判断完边界条件之后,对两个字符串的相同位置的索引的字符进行对比,来判断是否字符串相等,它有一个重载的方法,忽略字符串的大小写,在前面提到过,多了一个boolean
类型的参数,当值为true
的时候,就会按照忽略大小写进行比较字符串。