0

I have the following hierarchy :

abstract class customType<E extends Number>
class customInteger extends customType<Integer>
class customFloat extends customType<Float> 

to declare a LinkedList which accepts both customInteger and customFloat

List<customType<Number>> items = new LinkedList<customType<Number>>();

is this approach valid ?

Philipp Wendler
  • 11,184
  • 7
  • 52
  • 87
Suicidal
  • 55
  • 5

2 Answers2

2

customType<Number> is unrelated to customType<Integer>
So if you plan to add Integer or Float in items then this is not valid.
You can try the following:

List<CustomType<?>> items = new LinkedList<CustomType<?>>();

Use this as the collection for your items. To add the items you should use an auxiliary method as follows:

public static void addItemToList(List<? super CustomType<?>> l, CustomType<? extends Number> o){  
        l.add(o);  
}  

Then you can add to the list:

CustomFloat f = new CustomFloat();  
CustomInteger i = new CustomInteger();  
process(items, i);    
process(items, f);  
Cratylus
  • 52,998
  • 69
  • 209
  • 339
1

As stated by Cratylus, customType<Number>, customType<Float>, and customType<Integer> are three unrelated types, so this is not going to work. However, you can use List<customType<?>> as the type for items. Both customType<Float> and customType<Integer> are subtypes of customType<?> (which means "any customType, no matter what generic parameter value it has), and can thus be inserted into the collection.

Note that the Java convention is to start type names with an uppercase letter, so you should use the names CustomType, CustomInteger, and CustomFloat.

Philipp Wendler
  • 11,184
  • 7
  • 52
  • 87