for my education I have to write a basic Matrix in Java, in which you can put elements. The row and column of the elements should be implemented with a point and then i should connect the Point with the element in a map. There is the method put() with which i can put elements into this matrix, with the held of a HashMap. My problem now is that i cannot correctly see the element 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 it my get method only returns true and false. It should return true if there is an object at the row and column that the user puts in. But for some reason it always just returns false. I would be thankful for any help!!
Looking at your put method, it looks like you always put the same key (this.point) in the Map, and mutate that key. This is wrong, and will cause the same key to appear multiple times in the 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;
}
In addition, make sure your Point class overrides equals and hashCode.
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