java - HashMap not matching the value -
i have hashmap of buttons corresponding points in matrix. example in 3x3 matrix, btn0 @ (0,0) , on. point class 2 int variables coordinates. hashmap below:
public final static hashmap<button, point> buttonpoint = new hashmap<button, point>(); buttonpoint.put(btn0, new point(0,0)); buttonpoint.put(btn1, new point(0,1)); buttonpoint.put(btn2, new point(0,2)); buttonpoint.put(btn3, new point(1,0)); ...
i perform few calculations , come point (1,0). want button coordinates. following:
button selectedbutton = null; for(java.util.map.entry<button, point> entry : buttonpoint.entryset()){ if(objects.equals(selectedpoint, entry.getvalue())){ selectedbutton=entry.getkey(); } }
but selectedbutton still null. debugged code , see values equal @ point in iteration, still if condition never becomes true. there missing hashmaps ? or there other way of doing ? link or direction towards solution helpful. in advance.
if want button coordinates, using map<button, point>
not solution. should use map<point, button>
instead. way, need button @ given point is
button b = map.get(point);
and operation operates in constant time.
in both cases, need override equals()
, hashcode()
in point
. otherwise point never equal other point.
@override public boolean equals(object o) { if (o == null) { return false; } if (o == this) { return true; } if (o.getclass() != point.class) { return false; } point other = (point) o; return other.x == this.x && other.y == this.y; } @override public int hashcode() { return objects.hash(x, y); }
Comments
Post a Comment