如何在Java中使用泛型和语言运算符以及扩展Number的泛型类 [英] how to use generics in Java with language operators and generic class extending Number

查看:636
本文介绍了如何在Java中使用泛型和语言运算符以及扩展Number的泛型类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想对两个扩展Number的相同类型的两个泛型参数执行操作。



可能吗?
我总是用泛型参数调用方法,但似乎使用运算符时出现了一些问题(运算符+未定义参数类型T,T)。

  public static< T extends Number> T sum(T a,T b){
return a + b;
}

我做错了什么?



编辑:
我尝试改进一点我的问题。我明白运营商没有为Number类型定义。这件事有点令人难过,因为如果没有像@Victor Sorokin所建议的那样引入新界面,那么执行这样的操作会很好。

但我还是不明白一件事:如果运营商没有在类中实现Number,那么至少在Double类中应该实现,因为我可以使用+运算符双倍。
这两行代码都不会被编译:

  public static< T extends Double> T sum(T a,T b){

T c = a + b;
}

为什么?

解决方案

这是不可能的,因为 Number 没有与它关联的+运算符。特别是,你不能这样做:

  Number a = new Integer(1); 
数字b =新的整数(2);
数字c = a + b;


I would like to perform an operation on two generics argument of the same type both extending Number.

Is it Possible? I always used to call methods on generic arguments, but seems there is some problem using operators (The operator + is undefined for the argument type(s) T, T).

public static <T extends Number> T sum(T a, T b){
    return a+ b;
}

What am I doing wrong?

EDIT: I try to improve a little bit my question. I understood that operators are not defined for type Number. It's a bit sad this thing because it would be nice to perform such an operation without introducing new interfaces like suggested by @Victor Sorokin.

But I still don't understand one thing: if operators are not implemented in the class Number, then at least in Double class should be implemented because I can use + operator with double. Neither these line of code will compile:

public static <T extends Double> T sum(T a, T b){

    T c = a +b;
}

why?

解决方案

It's not possible because Number doesn't have a + operator associated with it. In particular, you can't do this:

Number a = new Integer(1);
Number b = new Integer(2);
Number c = a + b;

这篇关于如何在Java中使用泛型和语言运算符以及扩展Number的泛型类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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