String和一般的对象hashCode()运算区别

String和一般的对象hashCode()运算区别,第1张

String和一般的对象hashCode()运算区别 String重写了hashcode()方法,String类型的hash值是根据字符串的内容来决定的,并不是内存地址,只要两个String类型的字符串内容一致,那么两者的hashcode就相同。String为了节约内存比较特殊,因为很常用,所以定义为值一样的hashcode就一样,不同对象的hashCode 值一般来说不会相同,同一个对象的hashCode值肯定相同
package com.web;
public class Test55 {
    public static void main(String[] args) {
        String s1 = "abc";
        String s2 = "abc";
        String s3 = new String("abc");//new String()虽然灰色不可省略
        String s4 = new String("abc");//new String()虽然灰色不可省略

        boolean b2= s1==s2;//写法注意
        System.out.println("b2 = " + b2);//true

        System.out.println("s1==s2 = "+(s1==s2));//true 没有开辟新的内存空间,abc被s1,s2共享
        System.out.println("s1==s3 = "+(s1==s3));//false 开辟了新的内存空间
        System.out.println("s3==s4 = "+(s3==s4));//false
        System.out.println(s1.equals(s2));//true 只比较值大小
        System.out.println(s1.equals(s3));//true 只比较值大小

        System.out.println("s1.hashCode() = " + s1.hashCode());//96354
        System.out.println("s2.hashCode() = " + s2.hashCode());//96354
        System.out.println("s3.hashCode() = " + s3.hashCode());//96354
        System.out.println("s4.hashCode() = " + s4.hashCode());//96354

        System.out.println("-------------------------------------");
        Student stu1 = new Student("wang1", 11);
        Student stu2 = new Student("wang1", 11);
        Student stu0 = stu2;
        System.out.println("stu1.hashCode() = " + stu1.hashCode());//1580066828
        System.out.println("stu2.hashCode() = " + stu2.hashCode());//491044090
        System.out.println("stu0.hashCode() = " + stu0.hashCode());//491044090

        Student stu3 = new Student();
        Student stu4 = new Student();
        Student stu5 = stu4;
        System.out.println("stu3.hashCode() = " + stu3.hashCode());//644117698
        System.out.println("stu4.hashCode() = " + stu4.hashCode());//1872034366
        System.out.println("stu5.hashCode() = " + stu5.hashCode());//1872034366

        System.out.println("stu3 = " + stu3);
        System.out.println("stu4 = " + stu4);
        System.out.println("stu5 = " + stu5);

        Integer i1 = new Integer(100);
        System.out.println("i1.hashCode() = " + i1.hashCode());//100
        Integer i2 = 100;
        System.out.println("i2.hashCode() = " + i2.hashCode());//100
        boolean b = i1==i2;//包装类不可以这么比较
        System.out.println("b = " + b);//false
        System.out.println(i1.equals(i2));//true
    }
}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5609357.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-15
下一篇 2022-12-15

发表评论

登录后才能评论

评论列表(0条)

保存