I think the problem is that Java primitive arrays don't provide the right equals() and hashCode() for you. They use the standard Object methods that compare by object identity instead of contained values. When using nonscalar arrays as keys in a HashMap, Matlab will convert them to double[], but they'll be distinct Java objecs, so they'll get this behavior.
If you wrapped your array values in a Java object that provided by-value behavior for equals() and hashCode() before using them as keys, this could work. Luckily, java.util.Arrays provides by-value implementations for the primitive arrays. We just need to slap them in a wrapper class that provides the interface that HashMap is expecting.
package test;
import java.util.Arrays;
/**
* A double[] that with by-value semantics for equals() and hashCode() so you
* can use it in HashMaps.
* In a non-toy class, you'd probably use switch statements to support arrays
* of any primitive type. In a language with real generics, you'd just template
* this.
*/
public class EqualByValueDoubleArray {
private double[] x;
public EqualByValueDoubleArray(double[] x) { this.x = x; }
public double[] getArray() { return x; };
public boolean equals(Object obj) {
if (obj instanceof EqualByValueDoubleArray) {
return Arrays.equals(this.x, ((EqualByValueDoubleArray)obj).x);
} else {
return false;
}
}
public int hashCode() { return Arrays.hashCode(x); }
}
Now you can wrap them and use them as keys from Matlab.
function scratch_array_keyed_hashmap
import test.EqualByValueDoubleArray;
map = java.util.HashMap;
a = [1 2 3 4 5]';
key = EqualByValueDoubleArray(a);
map.put(key, 'my value');
% Separate key so we know it's comparing by value, not Java object identity
key2 = EqualByValueDoubleArray(a);
gotBack = map.get(key2)
This works under R2008b for me.
>> scratch_array_keyed_hashmap
gotBack =
my value
For easier use, you could create a HashMap subclass that checked the type of its input keys, and automatically wrapped primitive arrays in this by-value wrapper.