简体   繁体   English

Java泛型和简单类型

[英]Java generics and simple types

I was trying to write a generic class, that could operate on any simple type (int, float, etc.). 我试图编写一个泛型类,它可以在任何简单类型(int,float等)上运行。 I wanted to avoid repeating the same function several times, with changing the type of parameter. 我想避免多次重复相同的功能,改变参数的类型。 But since the generic parameter is a reference, I cannot do any calculations on variables of its type, like in C++ templates. 但由于泛型参数是一个引用,我不能对其类型的变量进行任何计算,就像在C ++模板中一样。

So is there any simple way in Java to use arithmetic operators on generic type variables? 那么在Java中有任何简单的方法在泛型类型变量上使用算术运算符吗? I know that I could use class-checking, and casting, but I think it would be much more code, and impact on performance. 我知道我可以使用类检查和转换,但我认为这将是更多的代码,并对性能产生影响。 However I only recently started to write in Java, so I may be wrong. 但是我最近才开始用Java编写,所以我可能错了。

There's no way to do this how you would in C++, sorry. 抱歉,你无法在C ++中做到这一点。 Generics in Java work quite differently to C++ templates. Java中的泛型与C ++模板的工作方式完全不同。 In Java, only one version of the generic code is ever generated, and it has to be suitable for all type arguments. 在Java中,只生成一个通用代码版本,并且它必须适用于所有类型参数。 Because all the primitives have different representations in byte code, they can't share the same generic code. 因为所有基元在字节代码中具有不同的表示,所以它们不能共享相同的通用代码。 This is why only reference types are valid type arguments in Java. 这就是为什么只有引用类型是Java中的有效类型参数。

I think the closest you could get would be to use the Number class. 我认为你能得到的最接近的就是使用Number类。 Autoboxing will automatically convert any primitive numeric value into a subclass of Number . Autoboxing会自动将任何原始数值转换为Number的子类。 Eg: 例如:

class Foo<T extends Number> {
  public void operate(T number) {
    double value = number.doubleValue();
    // do something with the double
  }
}
Foo<Integer> intFoo = new Foo<Integer>();
intFoo.operate(666);
intFoo.operate(666.0); // fails to compile

But the type parameter isn't really buying you much. 但是类型参数并没有真正为你买单。 And if you want the operate method to return a value of type T, you have to resort to runtime checks, which kind of defeats the purpose. 如果你想让operate方法返回一个类型为T的值,你必须求助于运行时检查,这种方法会失败。

A possibly interesting side note: Scala 2.8 will support an annotation @specialize that basically tells the compiler "handle the type arguments the C++ way", and generates a different version of the code for each different type argument representation. 一个可能有趣的旁注: Scala 2.8将支持注释@specialize ,它基本上告诉编译器“以C ++方式处理类型参数”,并为每个不同类型的参数表示生成不同版本的代码。

One solution could be to use a template method: 一种解决方案可能是使用模板方法:

T foo<T extends Number>( T value )

and do the calculations by using value.intValue() , value.longValue() , value.doubleValue() . 并使用value.intValue()value.longValue()value.doubleValue()

Java 1.5 should handle this for you through autoboxing Java 1.5应该通过自动装箱为您处理这个问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM