Java String的"==",equals和hashCode

public static void test_01(){
    String s1 = "hello";
    String s2 = "hello";
    String s3 = "hel"+"lo";
    String s4 = new String("hello");
    String s5 = new String("hello");
    String s6 = new String("hel"+"lo");
    System.out.println(s1==s2);
    System.out.println(s1==s3);
    System.out.println(s1.equals(s2));
    System.out.println(s1.equals(s3));
    System.out.println(s4==s5);
    System.out.println(s4==s6);
    System.out.println(s4.equals(s5));
    System.out.println(s4.equals(s6));
    System.out.println(s4.hashCode() == s5.hashCode());
    System.out.println(s4.hashCode() == s6.hashCode());
}

程序返回结果:
true
true
true
true
false
false
true
true
true
true

解释:
1."“是比较基本类型的值是否相等,或者比较两个引用变量是否相等(也即是两个对象的地址是否相等是否指向的是同一快存储空间),比较的是栈中的内容是否相等。
2.Object类中的equal方法直接使用的是”
"运算符比较的两个对象。在没有覆盖equal方法的情况下,equal 和“==”都是值比较,比较的都是引用,任何对象的equal都不等。
3.String 覆写了Object的equal方法和hashcode方法,用于比较两个独立对象的内容是否相同,也即比较的是堆中的内容是否相同。
4,。hashcode方法:返回的是对象在内存中的地址转成的一个int值,在没有覆盖hashcode方法的情况下,任何对象的hashcode值都不等。
5.hashcode约定:
如果equal比较的两个对象相等,hashcode值必须相等
如果equal比较的两个对象不相等,hashcode值不一定相等
如果hashcode比较的两个对象不等,equal必须不等
如果hashcode比较的两个对象相等,equal不一定相等

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值