Steven
Steven

Reputation: 1173

Equals with multiple values Java

I've made a Java class in which I simulate a Polynome (it contains an ArrayList<Pairs>, each pair has its own coefficient and exponent). But now I like to compare two Polynome's with the equals() method (with an Object).

I know I can't say that this == that because this will only compare the Polynome references. SO now I wondered if there's an easy way to compare both Polynome's values, or do I just have to check the first Pair of the first Polynome to the first Pair of the second Polynome etc.?

Upvotes: 0

Views: 1154

Answers (2)

biziclop
biziclop

Reputation: 49734

You have to override the equals() method of your Pair class to return true if and only if both the coefficient and the exponent are equal.

You should also override the hashCode() method if you override equals(). Although strictly speaking this isn't mandatory while you're using ArrayLists, it is good practice to always override equals() and hashCode() together.

Also note that because you're using a List, where the order of elements matters, x3+2x-1 won't be equal to 2x-1+x3, which is probably not what you want to see. You should store your Pair objects in a Set instead, as their equals() doesn't rely on the order in which you added the elements to them.

Upvotes: 1

duffymo
duffymo

Reputation: 308753

You have to override equals and check each and every Monomial in the Polynomial collection.

Hint: I'd have two classes - Monomial, with its own equals and hashCode, and a separate Polynomial, which would have a Set of Monomials and its own equals and hashCode.

Upvotes: 1

Related Questions