我正在学习 Lambda,我遇到了一些我无法解决的问题。
最初我的代码是:
package Lambdas;
@FunctionalInterface
interface NumericFunc2 {
<T extends Number> T func(T n);
}
class Lbd_488_NumericFunc_SelfTest {
public static void main(String args[]) {
// This block lambda returns the smallest positive factor of a value.
NumericFunc2 smallestF = (n) -> {
double result = 1;
// Get absolute value of n.
n = n < 0 ? -n : n;
for (int i = 2; i <= n / i; i++)
if ((n % i) == 0) {
result = i;
break;
}
return result;
};
System.out.println("Smallest factor of 12 is " + smallestF.func(12));
System.out.println("Smallest factor of 11 is " + smallestF.func(11));
}
}
但是,我的运算符旁边总是出现错误(<
、-
、/
)。
PS:就算我改成<T extends Double>
我遇到了同样的错误。
现在,如果我通过添加参数类型来更改代码,我会收到一条错误消息,指出“目标方法是通用的”:
即使我把它改成<T extends Double>
我遇到了同样的错误。
package Lambdas;
@FunctionalInterface
interface NumericFunc2 {
<T extends Number> T func(T n);
}
class Lbd_488_NumericFunc_SelfTest {
public static void main(String args[]) {
// This block lambda returns the smallest positive factor of a value.
NumericFunc2 smallestF = (Double n) -> {
double result = 1;
// Get absolute value of n.
n = n < 0 ? -n : n;
for (int i = 2; i <= n / i; i++)
if ((n % i) == 0) {
result = i;
break;
}
return result;
};
System.out.println("Smallest factor of 12 is " + smallestF.func(12));
System.out.println("Smallest factor of 11 is " + smallestF.func(11));
}
}
但是,如果我将类从非泛型更改为泛型,一切正常,如以下代码:
package Lambdas;
@FunctionalInterface
interface NumericFunc2<T extends Number> {
T func(T n);
}
class Lbd_488_NumericFunc_SelfTest {
public static void main(String args[]) {
// This block lambda returns the smallest positive factor of a value.
NumericFunc2<Double> smallestF = (n) -> {
double result = 1;
// Get absolute value of n.
n = n < 0 ? -n : n;
for (int i = 2; i <= n / i; i++)
if ((n % i) == 0) {
result = i;
break;
}
return result;
};
System.out.println("Smallest factor of 12 is " + smallestF.func(12));
System.out.println("Smallest factor of 11 is " + smallestF.func(11));
}
}
所以,我的问题是。我在代码的第一部分做什么工作?如何在非泛型类中正确使用带有泛型方法的 lambda?
最佳答案
答案是您不能对Number
对象执行这种数字运算。不可能; 这与 lambda 无关,与 Number
抽象类无关,只是不提供这些功能。
如果不知道 Number
是什么类型,甚至没有任何方法可以获取 Number
的绝对值。你看不出它是正还是负,你不能否定它,你不能加、减、乘。 唯一您可以对Number
做的事情是将其转换为另一种基本类型,但您不能将其转换回来,也不能用它进行数学运算。
关于java - Lambda 和泛型方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38427291/