0

I am new to programming, and I have come into a problem when trying to equate two instances of a custom class.

Here is a simple class I have created to easily work with fractional numbers in java:

public class Fraction {

int numerator;
int denominator;

Fraction(int n, int d) {
    numerator = n;
    denominator = d;
}

public String toString() {
    return numerator + "/" + denominator;
}

public double toDouble() {
    return (double) numerator / denominator;
}

}

When I attempt to determine whether two Fractions are equal, it always returns false, even in cases like:

new Fraction(1,1) == new Fraction(1,1) //returns false

How can I make instances of my class equatable?

Mark Anastos
  • 365
  • 3
  • 14
  • `==` compares the references of objects, `.equals()` compares their value. Look at the duplicate which is linked above to see how you should implement `.equals()` – Jeroen Vannevel Dec 11 '14 at 01:35
  • It's impossible to make `new Foo() == new Foo()` true, sadly. – August Dec 11 '14 at 01:36
  • @Mark - In Java, `==` always determines whether the _left_ and _right_ refer to the same object. So, if you have `Fraction a = new Fraction(1,1); Fraction b = a;` then `a == b` will be true. But there is nothing (in current version of Java) that will make `a == b` be true, if `a` and `b` are different objects, even if they are logically equal. You always need to use the `.equals` method to compare whether two objects are logically equal. In order to make that work, you need to implement the `equals` and `hashCode` methods as described in the duplicate. – Tim Dec 11 '14 at 01:41
  • @MarkAnastos That is the only way... You will also have to use this `equals` method instead of `==`. – Pshemo Dec 11 '14 at 02:06

0 Answers0