如何使 * 运算符在 java 中使用泛型变量? - 如果我知道变量是数字类型
How to make * operator working with generic variables in java? - if I know the variable is numeric type
这是我的通用 class。我尝试在 main 中创建并调用 length 方法,如果传递给构造函数的某个值是 Integer,我会得到 following error。如果所有三个参数都是双倍的,那就可以了。我也尝试使用 * 运算符而不是 Math.pow,但它也不起作用,因为 * 对于参数 N 是未定义的。所以...基本上,如果我知道它们是数字类型,我该如何乘以泛型变量 - "Number"
public class Test<N>{
public N x;
public N y;
public N z;
public Test(N arg1, N arg2, N arg3)
{
if (!(arg1 instanceof Number) || !(arg2 instanceof Number) || !(arg3 instanceof Number))
{
}
else
{
System.out.println("OK");
this.x = arg1;
this.y = arg2;
this.z = arg3;
}
}
public double length()
{
return Math.sqrt(Math.pow((double)x, 2) + Math.pow((double)y, 2) + Math.pow((double)z, 2));
}
}
Main:
System.out.println(new Test<>(2.56898,5.45,4.41).length()); // OK
System.out.println(new Test<>(2.56898,5,4).length()); // EXCEPTION
您可以只指定泛型的子类型,例如
public class Test<N extends Number> {
...
}
然后,不要使用 length
方法,而是使用适当的方法 doubleValue()
或您将来需要的任何方法,例如
public double length() {
return Math.sqrt(Math.pow(x.doubleValue(), 2) + Math.pow(y.doubleValue(), 2) + Math.pow(z.doubleValue(), 2));
}
这是我的通用 class。我尝试在 main 中创建并调用 length 方法,如果传递给构造函数的某个值是 Integer,我会得到 following error。如果所有三个参数都是双倍的,那就可以了。我也尝试使用 * 运算符而不是 Math.pow,但它也不起作用,因为 * 对于参数 N 是未定义的。所以...基本上,如果我知道它们是数字类型,我该如何乘以泛型变量 - "Number"
public class Test<N>{
public N x;
public N y;
public N z;
public Test(N arg1, N arg2, N arg3)
{
if (!(arg1 instanceof Number) || !(arg2 instanceof Number) || !(arg3 instanceof Number))
{
}
else
{
System.out.println("OK");
this.x = arg1;
this.y = arg2;
this.z = arg3;
}
}
public double length()
{
return Math.sqrt(Math.pow((double)x, 2) + Math.pow((double)y, 2) + Math.pow((double)z, 2));
}
}
Main:
System.out.println(new Test<>(2.56898,5.45,4.41).length()); // OK
System.out.println(new Test<>(2.56898,5,4).length()); // EXCEPTION
您可以只指定泛型的子类型,例如
public class Test<N extends Number> {
...
}
然后,不要使用 length
方法,而是使用适当的方法 doubleValue()
或您将来需要的任何方法,例如
public double length() {
return Math.sqrt(Math.pow(x.doubleValue(), 2) + Math.pow(y.doubleValue(), 2) + Math.pow(z.doubleValue(), 2));
}