java.lang.Number 没有实现“+";或任何其他运营商?
我正在创建一个类,它应该能够与任何类型的数字(float、int 等)的数组一起使用,所以这是我拥有的一种方法:
I'm creating a class which is supposed to be able to be used with an array of any type of number (float, int, etc), so here is one method I have:
// T extends Number
public synchronized T[] average() {
Number[] ret = new Number[queue[0].length];
for (int i = 0; i < ret.length; ++i) {
for (int j = 0; j < size; ++j) {
ret[i] += queue[j][i]; // WTF ERROR?!
}
ret[i] /= size; // WTF ERROR?!
}
return (T[])ret;
}
除了这不会编译,因为数字"没有实现+="或/="运算符.更糟糕的是,Java 的 Number 类甚至没有实现最基本的运算符,如+"或-"!如果java不让我编译它,我怎么能创建一个返回数字数组平均值的方法,因为它认为不能添加数字?!?!
Except this won't compile because "Number" doesn't implement the "+=" or "/=" operators. Event worse, java's Number class doesn't implement even the most basic operators like "+" or "-"! How can I make a method which returns the average of an array of Numbers if java won't let me compile it because it thinks that numbers can't be added?!?!
推荐答案
你误解了 Java 中数字的工作方式.Number
类是用于表示基本类型(int
、float
等)作为对象,但它确实不与通常的算术运算符一起使用.
You're misunderstanding the way numbers work in Java. The Number
class is the superclass of numeric wrapper classes (Integer
, Float
, etc.) useful for representing primitive types (int
, float
, etc.) as objects, but it does not work with the usual arithmetic operators.
如果您打算使用算术运算符,请使用原始类型.如果您需要构建适用于所有数字数据类型的通用"方法,您别无选择,只能构建同一方法的多个重载版本,每个数据类型一个,例如:
If you intend to use the arithmetic operators, then use primitive types. If you need to build a "generic" method that works for all numeric data types, you have no choice but to build several overloaded versions of the same method, one for each data type, for example:
public float[] average(float[][] queue) {...}
public double[] average(double[][] queue) {...}
还要注意,像这样的代码似乎适用于包装器类型:
Also be aware that code like this appears to work for wrapper types:
Integer i = 0;
i += 1;
System.out.println(i);
...但在底层,Java 自动 对 Integer
进行装箱和拆箱,因为 +=
运算符仅适用于原始类型.它之所以有效,是因为我们明确指出该数字是一个 Integer
,但它不适用于 Number
,因为 Java 需要准确地知道 什么 用于执行装箱/拆箱的数字类型.
... But under the hood, Java is automatically boxing and unboxing the Integer
, since the +=
operator only works for primitive types. It works because we're explicitly indicating that the number is an Integer
, but it won't work for a Number
, since Java needs to know exactly what type of number it's dealing with for performing the boxing/unboxing.
相关文章