tags:

views:

56

answers:

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

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)

+1  A: 

The class definition given by you is telling compiler that you would populate the list with only one particular sub class type of 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

Fazal
+3  A: 

This problem combines auto-boxing with generics. That ain't going to be pretty.

5 * Math.PI is a primitive double. To be converted to any type of Number object, it needs to be boxed. 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; be explicit and use Double in place of T.

If the class is going to be extended, and the number() method is to be overridden, you still know a concrete type. Declare the List (which you neglected to name) in the subclass with a matching type parameter.

erickson
Right. I want to preserve the ability to extend the class, in case I want a similar classes that uses Integers instead of Double.
Ben B.
@Ben B. - What do you want to do with the `Number` objects after they are added to the `List`?
erickson