java - Map which allows to provide the equals-comparator and the hashing function separately -
while trying model polynomials, in particular multiplication, run following problem. during multiplication, individual monomials of 2 polynomials multiplied , of course in can happen have (3x^2 y + 5x y^2) * (x + y). result contains 3x^2 y^2 , 5 x^2 y^2, want combine addition right away.
naturally use part x^2 y^2 of monomial key in (hash) map add different coefficients (3 , 5 in example). monomial object envisage should naturally contain coefficient, should not part of map key.
of course write equals/hashcode of monomial object such ignore coefficient. feels wrong, because mathematically monomial equal 1 if coefficients equal.
introducing coefficient-free monomial object intermediate operations not right.
instead of using map, use list , use binary search dedicated comparator ignores coefficient.
short of implementing map not use keys' equals/hashcode, dedicated one, there better ideas of how fuse monomials?
consider using treemap
, sortedmap
and map
. can provide comparator
constructor. sorted map use comparator
sorting map keys. importantly, case, consuder keys equal if comparator
returns 0. in case require comparator
not consustent equals, cause problems if not careful.
another option introduce class, acts adaptor mononomial
, can used map key having properties deserve.
Comments
Post a Comment