==、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指向的内存地址相同的。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值