说到String类型相信大家都见过==和equals的面试题。现在我们就从这一段代码开始学习。
使用==
进行比较
public static void main(String[] args) {
String a = "123";
String b = "123";
System.out.println(a == b); true
}
public static void main(String[] args) {
String a = new String("123");
String b = new String("123");
System.out.println(a == b); false
}
使用equals
进行比较
public static void main(String[] args) {
String a = new String("123");
String b = new String("123");
System.out.println(a.equals(b)); true
}
public static void main(String[] args) {
String a = "123";
String b = "123";
System.out.println(a.equals(b)); true
}
符号==
对于基本数据类型比较的是值,引用类型比较的是引用。equals
本质就是==
但是在String类型和Integer类型中重写了equals方法。下面我们就开始学习String类型的源码。
1、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
/** use serialVersionUID from JDK 1.0.2 for interoperability */
private static final long serialVersionUID = -6849794470754667710L;
value[]数组用来存储值,使用final修饰也就是说对String进行赋值之后就无法修改,只能重新生成一个新的地址进行存储。变量hash用来存放计算后的哈希值。
2、构造函数
// 无参构造函数,没有实在意义
public String() {
this.value = new char[0];
}
// 参数为String类型,进行保存并计算hash值
public String(String original) {
this.value = original.value;
this.hash = original.hash;
}
// 参数为char数组,使用Arrays.copyOf转换成String类型存储
public String(char value[]) {
this.value = Arrays.copyOf(value, value.length);
}
// 从下表offset开始读取count个字符写入value
public String(char value[], int offset, int count) {
if (offset < 0) {
throw new StringIndexOutOfBoundsException(offset);
}
if (count < 0) {
throw new StringIndexOutOfBoundsException(count);
}
// 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);
}
// StringBuffer 需要保证线程安全
public String(StringBuffer buffer) {
synchronized(buffer) {
this.value = Arrays.copyOf(buffer.getValue(), buffer.length());
}
}
3、String类型常用方法
charAt
public char charAt(int index) {
if ((index < 0) || (index >= value.length)) {
throw new StringIndexOutOfBoundsException(index);
}
return value[index];
}
返回对应位置的字符
codePointAt
public int codePointAt(int index) {
if ((index < 0) || (index >= value.length)) {
throw new StringIndexOutOfBoundsException(index);
}
return Character.codePointAtImpl(value, index, value.length);
}
用于返回对应下标的Unicode值
equals
public boolean equals(Object anObject) {
// 判断引用是否相同
if (this == anObject) {
return true;
}
// 判断是否是String类型
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) {
// 一旦出现不相同则返回false
if (v1[i] != v2[i])
return false;
i++;
}
return true;
}
}
return false;
}
equals
用于判断两个字符串是否相同。因为两个字符串的比较个逐个字符比较的如果两个超长的字符串比较是相当消耗时间的。equalse
常常与equals
搭配使用在一些集合类中,实现存储和快速定位。如:set、hashMap等
hashCode
public int hashCode() {
int h = hash;
// 判断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;
}
hashCode
在一些集合类中使用较多,可以通过计算hashCode
值作为下标进行存储、查询。使效率更高。
valueOf
public static String valueOf(char c) {
char data[] = {c};
// 调用构造函数返回String类型
return new String(data, true);
}
valueOf
的作用就是将其它类型转换成String类型,有int、long、float、double、char转换成String的方法。
intern
public native String intern();
intern是native方法的调用,它的作用是在方法区的常量池中开辟空间存储值,通过equals来查询。当常量池没有这个值就会开辟空间来存储。存在则使桟中的对象实例指向这个地址。
copyValueOf
public static String copyValueOf(char data[], int offset, int count) {
return new String(data, offset, count);
}
copyValueOf
实际就是返回一个新的值,通过构造函数传入offset位置和count长度来开辟新的空间返回新的String。
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
方法功能是去掉字符串两端空格符号,两端无论多少空格都会去掉。
substring
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);
}
substring
也就是返回在beginIndex到endIndex的字符串。常用于字符串的截取上。
replace
public String replace(char oldChar, char newChar) {
// 需要替换的字符和新的字符比较
if (oldChar != newChar) {
int len = value.length;
int i = -1;
char[] val = value; /* avoid getfield opcode */
// 先遍历查询是否有需要替换的字符
while (++i < len) {
if (val[i] == oldChar) {
break;
}
}
// i < len则表示有需要替换的
if (i < len) {
char buf[] = new char[len];
// 先保存不需要替换的
for (int j = 0; j < i; j++) {
buf[j] = val[j];
}
while (i < len) {
// 遍历字符串把需要替换的换成新的
char c = val[i];
buf[i] = (c == oldChar) ? newChar : c;
i++;
}
return new String(buf, true);
}
}
return this;
}
replace
方法是把所有旧的字符都换成新的,也就是替换掉某个字符。
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) {
// 判断从toffset位置开始的value是否和prefix一致
if (ta[to++] != pa[po++]) {
return false;
}
}
return true;
}
startsWith
作用是判断value从toffset开始的值是否和传入判断的字符串prefix一样。
总结
String对象赋值之后不可被修改的,每次都是new一个空间,而且value也是final修饰不可被修改的。以上就是一些比较常用的String类型的源码。