Java Array HashCode 实现 [英] Java Array HashCode implementation

查看:36
本文介绍了Java Array HashCode 实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这很奇怪.有同事问了java中myArray.hashCode()的实现.我以为我知道,但后来我进行了一些测试.检查下面的代码.我注意到的奇怪的事情是,当我写出第一个 sys 时,结果是不同的.请注意,这几乎就像是在报告内存地址并修改类移动了地址或其他内容.只是想我会分享.

This is odd. A co-worker asked about the implementation of myArray.hashCode() in java. I thought I knew but then I ran a few tests. Check the code below. The odd thing I noticed is that when I wrote the first sys out the results were different. Note that it's almost like it's reporting a memory address and modifying the class moved the address or something. Just thought I would share.

int[] foo = new int[100000];
java.util.Random rand = new java.util.Random();

for(int a = 0; a < foo.length; a++) foo[a] = rand.nextInt();

int[] bar = new int[100000];
int[] baz = new int[100000];
int[] bax = new int[100000];
for(int a = 0; a < foo.length; a++) bar[a] = baz[a] = bax[a] = foo[a];

System.out.println(foo.hashCode() + " ----- " + bar.hashCode() + " ----- " + baz.hashCode() +  " ----- " + bax.hashCode());

// returns 4097744 ----- 328041 ----- 2083945 ----- 2438296
// Consistently unless you modify the class.  Very weird
// Before adding the comments below it returned this:
// 4177328 ----- 4097744 ----- 328041 ----- 2083945


System.out.println("Equal ?? " +
  (java.util.Arrays.equals(foo, bar) && java.util.Arrays.equals(bar, baz) &&
  java.util.Arrays.equals(baz, bax) && java.util.Arrays.equals(foo, bax)));

推荐答案

java.lang.Array hashCode 方法继承自 Object,这意味着哈希码取决于引用.要根据数组的内容获取哈希码,请使用 Arrays.hashCode.

The java.lang.Array hashCode method is inherited from Object, which means the hashcode depends on the reference. To get the hashcode based on the content of the array use Arrays.hashCode.

注意虽然它是一个浅层的哈希码实现.还存在深度实现Arrays.deepHashCode.

Beware though its a shallow hashcode implementation. A deep implementation is also present Arrays.deepHashCode.

这篇关于Java Array HashCode 实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆