java - Must the .equals method for objects be overriden for instances of that object type in order for them to be used as keys in a HashMap -
i having trouble hashmaps. currently, hashmap hashmap of enum called names, using key of key signatures, or hashmap<keysignature, names>. currently, name enum stores values of keysignatures, or c_flat_major(new keysignature(7, accidental.flat, scale.major);. enum version of given keysignature, i've created hashmap explained above:
private static final hashmap<keysignature, names> lookup = new hashmap<keysignature, names>(); static { (names name : names.values()){ lookup.put(new keysignature(name.getkeysig()), name); } } so, when need check enum version of keysignature, call method, located in keysignature class:
public names getcommonname() { return names.lookup.get(this); } however, value returned null.
i cannot figure out causing this, seems if hashmap.get() method comparing key , argument reference rather value. have override .equals , .hash methods of keysignature, or looking in entirely wrong direction?
the answer yes.
if going create instances of keysignature on fly, equals method needs compare them "by value". default implementation of equals tests see if objects ==. so, need hashmap work, need override default equals , hashcode methods.
the other alternative replace code creates new instances of keysignature alternative code looks existing keysignature instance given combination of note, accidental , scale.
Comments
Post a Comment