java - For a HashMap that maps from a custom class, how to make it so that two equivalent keys will map to say value? -
i have custom class, example's sake let's it's tuples without order.
public class unorderedtuple { integer i1 = null; integer i2 = null; unorderedtuple(integer int1, integer int2) { i1 = int1; i2 = int2; } boolean equals(unorderedtuple t) { return t.i1 == i1 && t.i2 == t2 || t.i2 == i1 && t.i1 == i2; } }
like said, dumb example. now, let's have
map<unorderedtuple, integer> m = new hashmap<unorderedtuple, integer>();
ideally, i'd functionality:
unorderedtuple ut1 = new unorderedtuple(1,2); unorderedtuple ut2 = new unorderedtuple(2,1); m.put(ut1,2); m.put(ut2,3); system.out.println(m.get(ut1)==3); //ideally returns true
is there need implement or extend such can have functionality? in same way if use 2 different, equal strings, or integers, or whatever key map properly, if implement written, treats ut1 , ut2 separately. if construct ut1 , ut2 identically, same thing.
thanks help.
you need override hashcode()
... in case you'd xoring hash codes of fields involved, order-independence want.
you need override equals(object)
rather implementing equals(unorderedtuple)
.
i note you're using "==" compare instances of integer
: don't that. work in test case you've given due rules around boxing, if try values on 127 may run problems - it's comparing references rather values. call equals
compare values properly.
Comments
Post a Comment