java.lang.Number没有实现"+"或其他任何运营商? [英] java.lang.Number doesn't implement "+" or any other operators?

查看:94
本文介绍了java.lang.Number没有实现"+"或其他任何运营商?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个应该与任何类型的数字(浮点数,整数等)的数组一起使用的类,所以这里有一种方法:

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

除了不能编译,因为"Number"没有实现"+ ="或"/="运算符.更糟糕的是,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类是数字包装器类(IntegerFloat等)的超类,用于将原始类型(intfloat等)表示为对象,但它确实是 不能与普通的算术运算符一起使用.

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会自动

... 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.

这篇关于java.lang.Number没有实现"+"或其他任何运营商?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆