Java,object.hashCode(值改变9和10个字符)

时间:2017-01-23 13:14:05

标签: java hashcode

结果在OUT:

1956725890
356573597
1735600054
21685669
2133927002

代码:

public class Nemchinskiy {
    int date;
    String surname;


    Nemchinskiy(int n, String s) {

        date = n;
        surname = s;
    }

    public static void main(String[] args) {
        Nemchinskiy chelovek1 = new Nemchinskiy(30, "Roma");
        Nemchinskiy chelovek2 = new Nemchinskiy(30, "Roma");
        Nemchinskiy chelovek3 = new Nemchinskiy(30, "Roma");
        Nemchinskiy chelovek4 = new Nemchinskiy(30, "Roma");
        Nemchinskiy chelovek5 = new Nemchinskiy(30, "Roma");

        int hCode;
        hCode = chelovek1.hashCode();
        System.out.println(hCode);
        hCode = chelovek2.hashCode();
        System.out.println(hCode);
        hCode = chelovek3.hashCode();
        System.out.println(hCode);
        hCode = chelovek4.hashCode();
        System.out.println(hCode);
        hCode = chelovek5.hashCode();
        System.out.println(hCode);
    }}

问题:为什么是10位或9位?并且每一秒都是9强()

2 个答案:

答案 0 :(得分:2)

如果要覆盖哈希码,则使用该哈希码方法生成哈希码,否则将使用对象类的哈希码方法,并根据jvm中对象的地址/引用生成哈希码。

here

也有相同的哈希码关系

我希望我帮助过你。

答案 1 :(得分:0)

hashCode()返回获取对象引用的内存地址,并使用某种逻辑将其转换为整数格式。所以 hashCode()的结果也取决于内存。

这些是我的案例

  

案例:1

4072869
1671711
11394033
4384790
9634993
1641745

输出

public class HashCode9And10 
{
    int i;
    String s;

    public HashCode9And10(int i, String s) 
    {
        this.i = i;
        this.s = s;
    }

    public static void main(String[] args) 
    {
        HashCode9And10 h1 = new HashCode9And10(1, "asd");
        HashCode9And10 h2 = new HashCode9And10(1, "asd");
        HashCode9And10 h3 = new HashCode9And10(1, "asd");
        HashCode9And10 h4 = new HashCode9And10(1, "asd");
        HashCode9And10 h5 = new HashCode9And10(1, "asd");
        HashCode9And10 h6 = new HashCode9And10(1, "asd");

        System.out.println(h1.hashCode());
        System.out.println(h2.hashCode());
        System.out.println(h3.hashCode());
        System.out.println(h4.hashCode());
        System.out.println(h5.hashCode());
        System.out.println(h6.hashCode());
    }
}

在六个哈希码中,只有一个是8位数,其他是7位

  

案例:2

4072869
1671711
11394033
4384790
9634993
1641745

输出

ANativeWindow_setBuffersGeometry

这里输出模式也是相同的而不是10和9位数。所以会有所不同,数字的数量会有所不同。