Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java HashMap containsKey is returning false though key is present

Tags:

java

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

like image 432
somnathchakrabarti Avatar asked May 17 '26 05:05

somnathchakrabarti


2 Answers

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

like image 52
sethcall Avatar answered May 18 '26 21:05

sethcall


Have you (correctly) defined equals() and hashCode() in your MatrixIndex class?

like image 39
dty Avatar answered May 18 '26 20:05

dty