关于String的比较(一)

我们经常会遇到的一个面试题:


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]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值