0

この質問が以前にされていたら申し訳ありませんが、何を検索すればよいかわかりません。

とにかく、私は数学パッケージを作成しています。クラスの多くは Function を拡張します。

package CustomMath;

@SuppressWarnings("rawtypes")
public abstract class Function <T extends Function> {

    public abstract Function getDerivative();

    public abstract String toString();

    public abstract Function simplify();

    public abstract boolean equals(T comparison);

}

関数を比較して、それらが等しいかどうかを確認したい。それらが同じクラスのものである場合は、特定の比較メソッドを使用したいのですが、それらが異なるクラスのものである場合は、false を返したいと考えています。これが私が現在持っているクラスの1つです:

package CustomMath;

public class Product extends Function <Product> {

public Function multiplicand1;
public Function multiplicand2;

public Product(Function multiplicand1, Function multiplicand2)
{
    this.multiplicand1 = multiplicand1;
    this.multiplicand2 = multiplicand2;
}

public Function getDerivative() {
    return new Sum(new Product(multiplicand1, multiplicand2.getDerivative()), new Product(multiplicand2, multiplicand1.getDerivative()));
}

public String toString() {
    if(multiplicand1.equals(new RationalLong(-1, 1)))
        return String.format("-(%s)", multiplicand2.toString());
    return String.format("(%s)*(%s)", multiplicand1.toString(), multiplicand2.toString());
}

public Function simplify() {
    multiplicand1 = multiplicand1.simplify();
    multiplicand2 = multiplicand2.simplify();
    if(multiplicand1.equals(new One()))
        return multiplicand2;
    if(multiplicand2.equals(new One()))
        return multiplicand1;
    if(multiplicand1.equals(new Zero()) || multiplicand2.equals(new Zero()))
        return new Zero();
    if(multiplicand2.equals(new RationalLong(-1, 1))) //if one of the multiplicands is -1, make it first, so that we can print "-" instead of "-1"
    {
        if(!multiplicand1.equals(new RationalLong(-1, 1))) // if they're both -1, don't bother switching
        {
            Function temp = multiplicand1;
            multiplicand1 = multiplicand2;
            multiplicand2 = temp;
        }
    }
    return this;
}

public boolean equals(Product comparison) {
    if((multiplicand1.equals(comparison.multiplicand1) && multiplicand2.equals(comparison.multiplicand2)) || 
            (multiplicand1.equals(comparison.multiplicand2) && multiplicand2.equals(comparison.multiplicand1)))
        return true;
    return false;
}

}

これどうやってするの?

4

2 に答える 2

1

Object.equals(Object) メソッドをオーバーライドします。ここではジェネリックを使用する必要はありません。本体はこんな感じになります

if (other instanceof Product) {
    Product product = (Product) other;
    // Do your magic here
}

return false;
于 2014-01-07T21:36:25.447 に答える
1

ジェネリックを使用すると、 equals メソッドがタイプ「T」、この場合は「製品」にのみ適用されることが保証されます。別のクラス タイプを渡すことはできません。

別の可能性は、クラス関数の定義にあります。

public abstract boolean equals(Function comparison);

そして、classe Product では、オブジェクトの比較とcomparison instanceof Product

于 2012-10-06T23:08:22.643 に答える