简体   繁体   English

用于比较两个分数的覆盖 equals 方法

[英]Overriding equals method for comparing two fractions

I'm currently working on a project where I need to compare two fractions.我目前正在做一个项目,我需要比较两个分数。 I have not done such a thing before, overriding a method, so I need a little help.我以前没有做过这样的事情,覆盖了一个方法,所以我需要一点帮助。

Here is the thing that bothers me;这是困扰我的事情;

So I have a class called fraction, and in that class, I have two fields.所以我有一个叫做分数的类,在那个类中,我有两个字段。

public class Fraction {

private int denominator;
private int numerator;

public Fraction(int numerator, int denominator) {

    //Throwing an error if the denominator is 0.
    if (denominator == 0) {
        throw new IllegalArgumentException("Denominator cannot be zero!");
    }
    //When both numbers are negative
    if (denominator < 0 && numerator < 0) {
        denominator *= -1;
        numerator *= -1;
    }
    //When the numerator is negative
    if (denominator < 0 && numerator > 0) {
        denominator *= -1;
        numerator *= -1;
    }

    this.denominator = denominator;
    this.numerator = numerator;
}

public Fraction(int numerator) {
    this.numerator = numerator;
    this.denominator = 1;
}

public Fraction() {
    this.numerator = 0;
    this.denominator = 1;
}

I also have a couple of other useful methods for me to compare two fractions like this:我还有一些其他有用的方法来比较这样的两个分数:

//converts the current fraction to the lowest terms
public void toLowestTerms() {
    int reminder = 0, gcd = 0;
    int up = numerator, bottom = denominator;

    while (up != 0 && bottom != 0) {
        reminder = up % bottom;
        up = bottom;
        bottom = reminder;
        gcd = up;
    }
    numerator /= gcd;
    denominator /= gcd;
}

So here is the part I am stuck.所以这是我被卡住的部分。

@Override
//must take in an "Object" to properly override the Object class's equals method, but should ultimately check if two fractions are equal
public boolean equals(Object obj) {

    // If the object is compared with itself then return true
    if(obj == this){
        return true;
    }

    /* check if o is an instance of Complex or not
      "null instanceof [type]" also returns false */
    if (!(obj instanceof Fraction)) {
        return false;
    }

    //This object is created for
    Fraction compareObject = new Fraction(this.getNumerator(), this.getDenominator());
    compareObject.toLowestTerms();

    // typecast o to Fraction so that we can compare data members
    Fraction x = (Fraction) obj;

    //converting to the lowest terms to compare
    ((Fraction) obj).toLowestTerms();

    // Compare the data members and return accordingly
    return (compareObject.getNumerator()== x.getNumerator() && compareObject.getDenominator() == x.getDenominator());
}

Is this the right thing to do, or is there a way to do this properly?这是正确的做法,还是有办法正确地做到这一点? Technically I am creating an object to make use of the toLowestTerms method.从技术上讲,我正在创建一个对象来使用 toLowestTerms 方法。 Because when I want to compare, for example, 1/2 == 12/24, I need to reduce the numerator and denominator to do a good check.因为当我要比较的时候,比如1/2 == 12/24,我需要把分子和分母都缩小才能做好检查。

'Fraction compareObject = new Fraction(this.getNumerator(), this.getDenominator());
compareObject.toLowestTerms();`  

Your code seems good to me, I think it will work.您的代码对我来说似乎不错,我认为它会起作用。 I would add a few points, mostly about your comments:我想补充几点,主要是关于你的评论:

1. 1.

If the object is compared with itself then return true如果对象与自身进行比较,则返回 true

If the object is identical (ie the same instance)如果对象相同(即相同的实例)

2. 2.

instance of Complex Complex 的实例

You mean instance of Fraction ?你的意思instance of Fraction

3. It seems your method toLowestTerms changes the current instance this . 3. 似乎您的方法toLowestTerms更改了当前实例this For that reason, you created a new instance to represent this , called compareObject , I can only assume so that you don't alter this when compare is called (a good thing!).出于这个原因,您创建了一个新实例来表示this ,称为compareObject ,我只能假设您在调用 compare 时不会更改this (一件好事!)。 But for the parameter obj , you are altering the instance!但是对于参数obj ,您正在更改实例! You did not make a copy.你没有复制。 You can simply solve this by making the copy as well, but might I suggest that your toLowestTerms method returns a new copy of Fraction with the lowest terms?您也可以通过制作副本来简单地解决这个问题,但我可以建议您的toLowestTerms方法返回一个具有最低项的Fraction的新副本吗? Then you can safely call it on both this and obj , get fresh new copies, and compare both.然后你可以安全地在thisobj上调用它,获得新的副本,并比较两者。

4. A even more deep design decision would be to force call toLowestTerms on the constructor/setters. 4. 一个更深层次的设计决定是在构造函数/setter 上强制调用toLowestTerms So that it's impossible to have a Fraction that is not on the lowest terms.所以不可能有一个不在最低条件下的Fraction That would greatly simplify methods like equals , hashCode .这将大大简化诸如equalshashCode类的方法。 But that is a deeper design decision you would need to make.但这是您需要做出的更深入的设计决策。 If you do so, you can take a look at a library called Lombok who would generate equals and hashCode for you based on the properties of the class!如果这样做,您可以查看一个名为 Lombok 的库,它会根据类的属性为您生成 equals 和 hashCode! But will not do further calculations like toLowestTerms .但不会像toLowestTerms那样做进一步的计算。

5. If you are implementing equals, you probably want to implement hashCode as well, and make sure they are compatible. 5. 如果您正在实施 equals,您可能还想实施 hashCode,并确保它们兼容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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