Basic matrix in Java, get method doesn't work

for my education i have to write a basic matrix in java where you can put elements. The row and column of items must be implemented with a point, and then I must connect the point to an item in the map. There is a put () method with which I can put elements into this matrix using a HashMap. My problem is that I cannot see the element correctly in my map.

public boolean get(int row, int column) {
        Point p = new Point();
        p.x = column;
        p.y = row;
        if (matrixMap.containsKey(p)) return true;
        else return false;
    }

    public T put(int row, int column, T value) {
        point.x = column;
        point.y = row;
        this.matrixMap.put(this.point, value);
        return null;
    }

      

To test this, my get method returns true and false. It should return true if there is an object in the row and column that the user enters. But for some reason, it always just returns false. I would be grateful for any help!

+3


source to share


1 answer


Looking at your method put

, you always put the same key ( this.point

) in Map

and mutate that key. This is incorrect and will result in the same key appearing multiple times in Map

.

Change it to:



public T put(int row, int column, T value) 
{
    Point p = new Point();
    p.x = column;
    p.y = row;
    this.matrixMap.put(p, value);
    return value;
}

      

Also, make sure the class Point

overrides equals

and hashCode

.

+2


source







All Articles