在 Java 中使用数组作为哈希键?

use*_*406 5 java hashmap

我有一个函数可以进行一些计算。它接受一个 int 数组并根据传递给它的 int 数组的内容返回一个整数。

由于我的应用程序正在执行数百个这些计算,因此我正在尝试设置一种将这些计算结果存储在哈希图中的方法,这样它就不必重新计算它最近已经完成的计算。为此,我需要使用 int 数组作为哈希图的键。

目前这是打印尺寸 2,我希望它是打印尺寸 1:

LinkedHashMap hashmap = new LinkedHashMap();

int test[] = {1,2,3};
int test2[] = {1,2,3};

hashmap.put(test, 1);
hashmap.put(test2, 1);

System.out.println("Size: "+hashmap.size());
Run Code Online (Sandbox Code Playgroud)

实现这一目标的最佳方法是什么?我可以创建一种方法将数组转换为某种字符串编码数组数据,但我认为这不是最好的解决方案。

小智 5

它当前正在打印 2,因为它们是具有两个不同 hashCode 的两个不同数组,因此尽管它们具有相同的元素,但对于集合而言它们并不相同。您应该创建自己的对象,该对象具有一个数组作为对象内部的变量。然后它将覆盖 equals 和 hashCode 方法,以便根据数组中的值,该值将相同。

例如:

 public class MyClass
 {
        private int[] array;

       public boolean equals(Object o)
       {
           if(! (o instance of MyClass) ) return false;
           //loop through the arrays to see they are equal
         }

        public int hashCode()
       {  
           //loop through the array and return a number that is based off of the values in the array such as array[0] ^ array[1] + array[2] * array[3] / array[4] ...

        }
 }
Run Code Online (Sandbox Code Playgroud)

  • 你可以为你的两个函数使用 `Arrays.hashCode()` 和 `Arrays.equals()`。 (4认同)