I am using a HashMap data structure to store a SqMatrix (square matrix), where the key is of type MatrixIndex (which contains row and col) and the value is of type Integer.
But when I am getting false as output of "if (mat.containsKey(key))" though the HashMap has the corresponding key in it.
The main code:
public static void main(String[] args) {
Random generator = new Random();
int val = 0;
Types.MatrixIndex key, key1;
int matSz = (int) Math.floor(Math.sqrt(10));
Types.SqMatrix mat = new Types().new SqMatrix(matSz); //matSz*matSz elements
//HashMap<Types.MatrixIndex,Integer> hMap= new HashMap<Types.MatrixIndex,Integer>(10);
for (int r=0; r<matSz; r++) {
for (int c=0; c<matSz; c++) {
if (r<c) {
val = generator.nextInt(2) > 0? -1 : val;
key =(new Types()).new MatrixIndex(r, c);
key1 = (new Types()).new MatrixIndex(c, r);
mat.put(key, val);
mat.put(key1, val);
generator.setSeed(System.currentTimeMillis());
}
}
}
for (int r=0; r<matSz; r++) {
val = 0;
for (int c=0; c<matSz; c++) {
if (r!=c) {
key = (new Types()).new MatrixIndex(r, c);
if (mat.containsKey(key)) {
val = val + mat.get(key);
}
}
}
key1 = (new Types()).new MatrixIndex(r, r);
mat.put(key1, val);
}
Do anybody have an idea on why the containsKey is returning false though it is present in the HashMap?
Thanks in advance,
Somnath
I have no idea what MatrixIndex is, but if it's hashcode implementation isn't overridden, then every instance of MatrixIndex has it's own hashcode, and is considered unique. Therefore, you can't pass in a new instance of MatrixIndex to do a containsKey() check.
If you want that exact code snippet to work, you need to override equals() and hashcode() in your MatrixIndex class, and make it so that it always creates a reproducible, unique value for that class.
If you haven't done this before, definitely read up on overriding these two methods. A quick search will bring up a great deal of help. If you can add new libraries to your project, look at: http://commons.apache.org/lang/api-2.4/org/apache/commons/lang/builder/HashCodeBuilder.html
Have you (correctly) defined equals() and hashCode() in your MatrixIndex class?
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