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.
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] ...
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With