==、equals()和hashCode()字符串测试
1、hashCode() 是根据 内容 来产生hash值的
2、System.identityHashCode() 是根据 内存地址 来产生hash值的。我们知道,new出来的String对象的内存地址是不一样的,所以hash值也不一样
代码:
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指向的内存地址相同的。
So 字符串的对比跟变量的初始化方式有关,谨慎!