Java, object.hashCode(数值变化9和10位数)

Java, object.hashCode(values change 9 and 10 figits)

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强)(

如果你要重写hashcode,那么hashcode会使用那个hashcode方法生成,否则会使用Objectclass的hashcode方法,它根据address/reference的hashcode生成hashcode jvm中的对象。

还有相等和hashcode的关系here

希望对你有所帮助。

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

这些是我的案例

Case : 1

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

        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());
    }
}

输出

4072869
1671711
11394033
4384790
9634993
1641745

看到6个hashcode只有一个是8位的,其他都是7位的

Case : 2

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());
    }
}

输出

4072869
1671711
11394033
4384790
9634993
1641745

这里的输出模式也是一样的,不是 10 位和 9 位数字。所以会有差异,位数会有所不同。