gpt4 book ai didi

java - 如何限制方法仅接受具有某些限制的参数?

转载 作者:行者123 更新时间:2023-11-30 03:38:40 25 4
gpt4 key购买 nike

我有以下 Duple 类,我正在尝试编写方法来对其两个“单元格”执行数学运算 ((new Duple(1,2)).plus(new Duple(2,6 ) == new Duple(3,8)):

final class Duple<T,U> {
final T a;
final U b;
public Duple(T a, U b) { this.a = a; this.b = b; }

public String toString() {
return "(" + a + ", " + b + ")";
}

/*public Duple<T,U> plus(Duple <T,U> otherDuple) {
return Duple(a + otherDuple.a, b + otherDuple.b);
}*/

注释掉的代码会出错,因为它不能保证 TU 支持 +。有没有办法让它对参数进行编译时检查?

我尝试过:

public Duple<T,U> plus(Duple <T extends Number,U extends Number> otherDuple) { ... }

但是编译器提示我删除extends。我看到了一个使用用户定义接口(interface)的示例,但对于我需要它的用途来说,这似乎很极端。

基本上我正在尝试模仿:

plus :: (Num t, Num u) => Duple t u -> Duple t u -> Duple t u
(x1,y1) `plus` (x2,y2) = (x1 + x2,y1 + y2)

如果它是用 Haskell 编写的

最佳答案

您不能拥有仅存在于类的某些实例中的方法。

相反,您可以对类的类型参数施加约束。

关于java - 如何限制方法仅接受具有某些限制的参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27261950/

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