简体   繁体   中英

public boolean equals(Object other)

This is for a Fraction program. I have private ints num and den, Fraction, and FractionInterface - the standard homework problem. I have done pretty much everything and now have been stuck for a few hours on the equals method. Since other is an Object, I can't equate it to Fraction. Here's what I have:

public boolean equals(Object other){        
     if (other == this){
         return true;
     } else {
         return false;
     }
}

This compiles but it gives incorrect results:

1/2 eq 1/2 = true
1/2 eq 1/2 = true
1/2 eq 1/2 = false
1/2 eq 1/2 = false

If I try other == Fraction, it doesn't compile. Thanks for any help!

You can test if other is an instance of FractionInterface and use a cast:

public boolean equals(Object other){        
     if (other == this){
         return true;
     } else if (other instanceof FractionInterface) {
         FractionInterface fOther = (FractionInterface) other;
         // compare numerator and denominator...
     } else {
         return false;
     }
}

Note that instanceof will be false if other == null , so there's no need for a separate null check.

Try this out:

First, cast the other object

Fraction otherFraction = (Fraction) other;

Then, determine the condition that the two fractions are equivalent. This will include some logic involving the comparing of numerator and denominators (expect to use getNum() and getDen() for the otherFraction .

You should check whether the argument is an instance of your class and return false if it isn't and cast it to your class and compare according to your needs if it is. It's common to write equals() method like this:

public boolean equals(Object obj) {
    if (!(obj instanceof Fraction)) {
        return false;
    }
    Fraction that = (Fraction) obj;
    ... // Your algorithm to compare two fractions: this and that.
}

You should make sure that your algorithm for comparing two fractions meets all the requirements described in equals() documentation .

You need to test if the object has the Fraction class, and if so, cast it to a Fraction:

if (other.getClass() != Fraction.class) {
    return false;
}
Fraction otherFraction = (Fraction) other;
// compare the fields of this and otherFraction

Before doing this, make sure to also test for null.

You are comparing that the two objects references refer to the same object.

You will need to check that the other is of type Fraction and then type cast it to a Fraction . You are then about to compare the two parts of the Fraction .

I think you're close, but you're missing a few key concepts. This is because your as is won't work in all situations. Try this for example using your existing code...

Fraction a = // this is however you're making a fraction object...
Fraction b = // do EXACT same thing here that you did for a

// And then, this will illustrate what is wrong with your program...
if(a.equals(b)) {
  System.out.println("This won't print");
} else {
  System.out.println("This will print because your method just checks for reference");
}

So here are the basics you need to understand:

  1. Difference between == and equals
  2. Comparing type as opposed to reference or value
  3. Avoiding casting by putting your "equals" method in the proper place

First off...

public boolean equals(Object other){        
     if (other == this){
         return true;
     } else {
         return false;
     }
}

You're missing the point of the "equals" method in Java. == is used to compare references while this.equals(foo) is used to put the logic for comparing objects in a localized place.

The other concept you're missing is how instanceof should be used. When you ask this...

If I try other == Fraction, it doesn't compile.

This is because you're looking to compare the type of the object. To do this, you would simply do...

if(other instanceOf Fraction) {
  // do stuff...
}

All of that being said, there is one last concept, which is putting the equals definition in the proper place. You need to put it inside your Fraction class and define it like this...

public boolean equals(Fraction other) {
  // do something like this (you will have to define toDouble)
  if(this == other || this.toDouble() == other.toDouble()) {
    return true;
  }

  return false;
}

This will override the default...

public boolean equals(Object other) {/* ... */}

And it will make it EXTREMELY convenient. Here is some sample code of how...

Fraction fractionA = new Fraction("2/4");
Fraction fractionB = new Fraction("1/2");
Fraction fractionC = new Fraction("1/3");
Object trollObject = new Object();

// And then call random equals objects...
if(fractionA.equals(fractionB)) {
  // should be true...
}

if(fractionB.equals(fractionA)) {
  // should be true...
}

// This avoids having to do any casting because
// since you've only defined a Fraction.equals(Fraction) method
// it should instead default to the Object.equals method
if(trollObject.equals(fractionB)) {

}

Here's a quite standard pattern:

public boolean equals(Object other) {
    if (other == this) return true;
    if (other == null) return false;
    if (other.getClass() != this.getClass()) return false;

    Fraction o = (Fraction) other;
    // now you compare their num, den, and possibly sign
}

People may argue if we should use getClass() or instanceof . It matters only if Fraction is extended, and it depends on what you want if it is extended. Just keep in mind a contract of equals() is a.equals(b) should get the same result as b.equals(a) if neither one is null , and a subclass may have a different equals() that potentially breaks the contract.

I hope that it will helpful to you .try this code.

import java.io.*;

class Cast

{

public static void main(String args[]) throws IOException

{

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

byte a=20;

short s=31468;

int i=12345678;

char c=’c';

float f=3.56f;

//Widening or promotion [java question bank][1]

System.out.println(“a=(short)  “+(short) a);

System.out.println(“a=(int)  “+(int) a);

System.out.println(“a=(long)  “+(long)a);

System.out.println(“a=(float)  “+(float)a);

System.out.println();

System.out.println();

System.out.println(“s=(int) “+(int)s);

System.out.println(“s=(long)  “+(long)s);

System.out.println(“s=(float)  “+(float)s);

System.out.println();

System.out.println();

System.out.println(“i=(long)  “+(long)i);

System.out.println(“i=(float)  “+(float)i);

System.out.println(“i=(double)  “+(double)i);


//Narrowing using [java question bank][2]

System.out.println(“f=(byte)  “+(byte)f);

System.out.println(“f=(short)  “+(short)f);

System.out.println(“f=(char)  “+(char)f);

System.out.println(“f=(long)  “+(long)f);

System.out.println();

System.out.println();

System.out.println(“i=(byte)  “+(byte)i);

System.out.println(“i=(short)  “+(short)i);

System.out.println();

System.out.println();

System.out.println(“s=(byte)  “+(byte)s);


}

}

== operator compares hash codes of objects. That is reason why your method is not ok, you should write it like this :

public boolean equals(Object other){        
     if (other instanceof Fraction){
         return ((Fraction)other).getNum == this.num && ((Fraction)other).getDen == this.den;
     } else {
         return false;
     }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM