首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

==、equals()跟hashCode()字符串测试

2012-10-07 
、equals()和hashCode()字符串测试public class Test {public static void main(String[] args) {?? Stri

==、equals()和hashCode()字符串测试

public class Test {
public static void main(String[] args) {
?? String a=new String("foo");
?? String b=new String("foo");
??
?? String c="hello";
?? String d="hello";
??
?? System.out.println("memory address hashcode a:"+System.identityHashCode(a));
?? System.out.println("memory address hashcode a:"+System.identityHashCode(b));
?? System.out.println("String hashcode a:??????? "+a.hashCode());
?? System.out.println("String hashcode a:??????? "+b.hashCode());
?? System.out.println("a==b:???????????????????? "+(a==b));
?? System.out.println("a.equals(b):????????????? "+a.equals(b));
??
?? System.out.println("");
??
?? System.out.println("memory address hashcode c:"+System.identityHashCode(c));
?? System.out.println("memory address hashcode d:"+System.identityHashCode(d));
?? System.out.println("String hashcode c:??????? "+c.hashCode());
?? System.out.println("String hashcode d:??????? "+d.hashCode());
?? System.out.println("c==d:???????????????????? "+(c==d));
?? System.out.println("c.equals(d):????????????? "+c.equals(d));
}
}


输入结果:
memory address hashcode a:8222510
memory address hashcode a:18581223
String hashcode a:??????? 101574
String hashcode a:??????? 101574
a==b:???????????????????? false
a.equals(b):????????????? true

memory address hashcode c:3526198
memory address hashcode d:3526198
String hashcode c:??????? 99162322
String hashcode d:??????? 99162322
c==d:???????????????????? true
c.equals(d):????????????? true


结论:
==比较的是对象的地址
equals比较的是被String类重写的对比字符串的内容值
hasCode也是被String重写,已经不是对象内存地址的hash码,因为a、b是两个完全不同的对象,也满足这条规律“equals相等的两个对象,hasCode也相等”。
System.identityHashCode是未被重写的获取对象内存地址hash码的函数,可以发现a、b的内存地址不同

c、d的比较结果全部一致,这是java的一种优化 ,它会先把"hello"这个字符串放在字符缓冲区中,如果有出现一个String x = "hello",就直接把缓冲区中的地址赋给x,就会出现c与d指向的内存地址相同的。

热点排行