简体   繁体   English

如何对泛型使用不同的方法

[英]How to use different methods with generics

public class MyGenerics<T extends Number>{
   List<T> = new ArrayList<T>();

   public void addToList(){
     for (ListIterator<T> it; it.hasNext(); ){
         it.next();
         it.add(number());
     }
   }

   public T number(){
     return (T) 5*Math.pi;
   }
}

As far as I can tell, there is no way to tell the compiler "I promise, everything that is returned by number() is some object that extends Number and will be cast to type T, whatever it is, because I am casting it. 据我所知,没有办法告诉编译器“我保证,由number()返回的所有内容都是某个扩展Number的对象,无论它是什么,都将被强制转换为T类型,因为我正在强制转换。

I am new to generics, so any help is greatly appreciated. 我是泛型新手,所以对您的帮助非常感谢。 I got around this by subclassing the class, but that semi-misses the point of generics. 我通过对类进行子类化解决了这个问题,但这半遗漏了泛型的观点。

And please note that the issue isn't really about adding just one value to a list. 并且请注意,问题实际上并不是在列表中仅添加一个值。 The issue is the generics logic. 问题是泛型逻辑。 (Just to be clear) (只是要清楚)

This problem combines auto-boxing with generics. 此问题将自动装箱与泛型结合在一起。 That ain't going to be pretty. 那不会很漂亮。

5 * Math.PI is a primitive double . 5 * Math.PI是原始的double To be converted to any type of Number object, it needs to be boxed. 要转换为任何类型的Number对象,需要将其装箱。 So, the compiler needs to know the concrete target type for the boxing operation, but it is missing because you are using generics. 因此,编译器需要知道装箱操作的具体目标类型,但是由于使用的是泛型,因此缺少该目标类型。

If the class is not extended, and number() always returns a double (or Double ), don't use use generics; 如果该类未扩展,并且number()始终返回double (或Double ),请不要使用use泛型; be explicit and use Double in place of T . 是明确的,并使用Double代替T

If the class is going to be extended, and the number() method is to be overridden, you still know a concrete type. 如果要扩展该类,并且要重写number()方法,您仍然知道具体的类型。 Declare the List (which you neglected to name) in the subclass with a matching type parameter. 在子类中使用匹配的类型参数声明List (您忽略的名称)。

The class definition given by you is telling compiler that you would populate the list with only one particular sub class type of Number. 您给定的类定义告诉编译器您将仅使用Number的一种特定子类类型填充列表。

If you want to mix sub classes, then you should define your method as following 如果要混合子类,则应按以下方式定义方法

public Number number(){
    return 5*Math.PI;
}

and remove this entire type variable as your method cannot guarantee that all children would be double type 并删除整个类型变量,因为您的方法不能保证所有子代都为双精度类型

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

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