我们经常会遇到的一个面试题:
[table]
|Answers: |[color=red]true,true,true,true,false,true[/color]|
[/table]
[size=large][b]Why?[/b][/size]
首先我们看String的eqauls方法:
到这儿我们可以知道两次调用equals肯定相等了
然后我们来看String的hashCode()方法
[size=large][color=red][b]那还有一个问题,==,为啥第一次是true,第二次是false呢?后续分解[/b][/color][/size]
public class StringTest {
public static void main(String args[]) {
String a = "hello";
String b = "hello";
System.out.println(a.equals(b));
System.out.println(a == b);
System.out.println(a.hashCode() == b.hashCode());
String c = new String("hello");
String d = new String("hello");
System.out.println(c.equals(d));
System.out.println(c == d);
System.out.println(c.hashCode() == d.hashCode());
}
}
[table]
|Answers: |[color=red]true,true,true,true,false,true[/color]|
[/table]
[size=large][b]Why?[/b][/size]
首先我们看String的eqauls方法:
public boolean equals(Object anObject) {
if (this == anObject) {//比较两个对象的内存地址
return true;
}
if (anObject instanceof String) {//判断是否是String类型
String anotherString = (String) anObject;
int n = count;
if (n == anotherString.count) {//比较两个String对象的长度
char v1[] = value;
char v2[] = anotherString.value;
int i = offset;
int j = anotherString.offset;
while (n-- != 0) {//比较两个String中每个字符是否相等
if (v1[i++] != v2[j++]) return false;
}
return true;
}
}
return false;
}
到这儿我们可以知道两次调用equals肯定相等了
然后我们来看String的hashCode()方法
public int hashCode() {
int h = hash;//hash的默认值是0
if (h == 0) {//如果等于0则重新计算当前String对象的hash值,否则说明hash值已经计算过
int off = offset;
char val[] = value;
int len = count;
//计算hash值,如果两个String每个字符都相等的话,接下来的算法算出来的hash值肯定相等
for (int i = 0; i < len; i++) {
h = 31 * h + val[off++];
}
hash = h;
}
return h;
}
[size=large][color=red][b]那还有一个问题,==,为啥第一次是true,第二次是false呢?后续分解[/b][/color][/size]