Java通用类型编号 [英] Java Generic Type Number

查看:62
本文介绍了Java通用类型编号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经阅读了几篇有关泛型方法的文章,并对它们有所了解,但我仍然不理解它们.假设我有一个将两个数字相乘并返回乘积的方法:

I have read several pages on generic methods and have some sort of grasp on them, but I still don't understand them. So say I have a method to multiply two numbers and return the product:

public double multiply(SomeNumberVariableType x, SomeNumberVariableType y){
    return x * y;
}

如何使用有界泛型仅允许将数字类型用作参数?

How can I use bounded generics to have only a number type permitted as parameters?

推荐答案

也许这是您的意图:

public static <N extends Number> double multiply(N x, N y){
    return x.doubleValue() * y.doubleValue();
}

尽管我也必须说,使用Number代替诸如Java原语double之类的具体的不可变值类型的一般用法可能不太健康,因为在上面的示例中,参数甚至可以是不同的类型,例如Integer和Double

Although I must also say that the generic use of Number instead of concrete immutable value types like java primitive double is probably not so healthy because in the example above the arguments could even be of different types, for example Integer and Double.

注意:

我确认,自变量可以是上面给出的签名所用的不同类型.因此,波希米亚的答案是错误的.我刚刚测试了它(但之前已经知道了).编译器仅保证两个参数的类型均为Number,没有其他任何内容.

I confirm, the arguments can be of different types as given signature above. So the answer of Bohemian is wrong. I have tested it just now (but knew it already before). The compiler only guarantees that both arguments are of type Number, nothing else.

为了声明相同的参数类型,编译器需要自引用泛型. Number-class无法满足此功能(不幸的是,< N扩展Number< N>是不可能的).这就是为什么我认为整个数字方法并不十分健康.这里是每个人都可以执行的测试代码:

In order to assert the same argument types the compiler needs self-referencing generics. This feature is not fulfilled by Number-class (that is <N extends Number<N>> is unfortunately not possible). That is why I consider the whole Number approach as not really healthy. Here a test code which everyone can execute:

Integer x = Integer.valueOf(10);
Double y = new Double(2.5);
System.out.println(multiply(x, y));
// Output: 25.0

这篇关于Java通用类型编号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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