Issue whilst comparing instances with HashMaps in Java -
i trying value hashmap via custom class have created.
the custom class:
public class coordinates { private int x; private int y; public coordinates(int x, int y) { this.x = x; this.y = y; } public int getx() { homecoming this.x; } public int gety() { homecoming this.y; } public boolean issame(coordinates coords) { if (coords.getx() == this.x && coords.gety() == this.y) { homecoming true; } homecoming false; } public string getasstring() { homecoming "("+this.x+", "+this.y+")"; } public coordinates getcoords() { homecoming this; } } i have hashmap called coordsjcb , when seek jcbutton (a custom swing button) says cannot find it.
private static hashmap<coordinates, jcbutton> coordsjcb = new hashmap<coordinates, jcbutton>(); coordsjcb.get(coords); i did little debugging , noticed that
system.out.println(new coordinates(2, 3).equals(new coordinates(2, 3))); printed false, though same. googled , got many answers overriding .equals function. not help me don't want compare 2 instances of 'coordinates', need value hashmap passing instance of coordinates.
any help much appreciated have absolutely no thought do. :/
the hashmap's key set hashes elements , compares them hash.
you need override object.hashcode , object.equals in coordinates class.
your equals method should homecoming true when x , y equal othercoordinates.x , othercoordinates.y respectively.
for hashcode it's bit trickier because hash based on 2 ints, need find way avoid weak hashes (i.e. duplicated hashes).
your ide's boilerplate hashcode implementation functionalities should help out there, can additional bit shifting , utilize improve prime seeds.
for instance in ecplise:
right-clickcoordinates class click source click generate hashcode() , equals()... java hashmap instance
No comments:
Post a Comment