Java – allows you to provide maps for equals comparator and hash functions, respectively

When trying to model polynomials, especially their multiplication, I encountered the following problems During multiplication, the single monomial of two polynomials can be multiplied. Of course, I have (3x ^ 2 y 5x y ^ 2) * (x y) The results include 3x ^ 2 y ^ 2 and 5x ^ 2 y ^ 2, which I want to combine immediately by adding

Of course, I want to add different coefficients (3 and 5 in the example) using the part X ^ 2, y ^ 2 of the monomial as the keyword in the (hash) map However, the monomial object I imagine should naturally contain a coefficient, which should not be part of the map key

Of course, I can write the equals / hashcode of individual objects so that they ignore the coefficients But this feels wrong, because mathematically, a monomial is obviously equal to only one other if the coefficients are equal

It also seems incorrect to introduce a coefficient - free monomial object for intermediate operations

Instead of using maps, I use lists and binary searches and a dedicated comparator that ignores coefficients

If you don't use maps that don't use the key 'equals / hashcode, but use dedicated maps, is there a better idea of how to integrate monomials?

Solution

Consider using treemap, which is a SortedMap and therefore a map You can provide comparator. For its constructor An ordered map uses the comparator to sort the mapping keys But importantly, in your case, if the comparator returns 0, it will equalize the consumer key In your case, you need a comparator that is not equal to equals. If you are not careful, it may cause problems

Another option is to introduce another class that acts as an adapter for mononomial and can be used as a mapping key with the attributes you deserve

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>