Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using an array as a hash key in Java?

Tags:

java

hashmap

I have a function that does some calculations. It accepts a int array and returns an integer based on the contents of the int array that's passed to it.

As my application is doing hundreds of theses calculations I'm trying to set up a way to store those calculation results in a hashmap so it don't have to recalculate the calculation it already did recently. To do this though I'd need to use the int arrays as my keys to the hashmap.

At the moment this is printing size 2, I want it to be printing size 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());

What's the best way to achieve this? I could create a method to convert the arrays to some kind of string encoding the arrays data but I don't think that would be the best solution.

like image 634
user11406 Avatar asked Oct 20 '22 17:10

user11406


1 Answers

It is currently printing 2 because they are two different arrays with two different hashCodes, so although they have the same elements, they are not the same for the purposes of a set. You should create your own object which has an array as a variable inside of the Object. Then it will override the equals and hashCode method so that the value will be the same based on the values in the array.

e.g.:

 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] ...

        }
 }
like image 184
Gregory Basior Avatar answered Oct 22 '22 09:10

Gregory Basior