gpt4 book ai didi

Java 子类化泛型参数

转载 作者:行者123 更新时间:2023-12-02 07:32:11 25 4
gpt4 key购买 nike

如果之前有人问过这个问题,我很抱歉,但我真的不知道要搜索什么。

无论如何,我正在制作一个数学包,并且许多类都扩展了 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。这是我目前的类(class)之一:

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;
}

}

我该怎么做?

最佳答案

使用泛型,您可以保证 equals 方法仅适用于类型“T”,在本例中为“Product”。您无法传递其他类类型。

另一种可能性是在类函数定义中:

public abstract boolean equals(Function comparison);

在 Product 类中,对象与 comparison instanceof Product 进行比较

关于Java 子类化泛型参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12764597/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com