I'm sure I'm probably missing something fairly obvious here, but is there a reason why:
ArrayList<? extends Number> list = new ArrayList<Number>();
is allowed, but:
ArrayList<T extends Number> list = new ArrayList<Number>();
is not?
I'm sure I'm probably missing something fairly obvious here, but is there a reason why:
ArrayList<? extends Number> list = new ArrayList<Number>();
is allowed, but:
ArrayList<T extends Number> list = new ArrayList<Number>();
is not?
Because, with:
ArrayList<? extends Number> list = new ArrayList<Number>(); //OK
you are defining the concrete object of type ArrayList generalized with upper bounded wildcard <? extends Number>.
Type of your wildcard will match any sub-type of Number, which means that you can assign to your list variable, any ArrayList specialized with any type which extends Number:
list = new ArrayList<Float>(); //will work fine
list = new ArrayList<Double>(); //will work fine
list = new ArrayList<String>(); //will NOT work as String does not extend Number
The only caveat is the Capture Problem. You won't be able to add Number extender instances in your list.
In here, however:
ArrayList<T extends Number> list = new ArrayList<Number>(); //Syntax error
you have a syntax error in your object declaration. You are using bounded type parameter to declare your variable; however, bounded type parameter is used to define a generic class/type or generic method.
Type parameter T, or any (preferably capital) letter, is used to declare a generic type parameter when you define your class (or method).
For example, your upper-bounded generic type in this definition:
public class YourClass<T extends Number> {
....
}
will become a real type, at run-time, when you will declare your YourClass type by providing some real type, as a generic type argument, like this:
YourClass<Integer> ints; //will work fine
YourClass<Double> doubles; //will work fine
YourClass<Float> floats; //will work fine
YourClass<String> strings; //will NOT work, as String does not extend Number
Pay attention, that here as well, T extends Number matches any type that extends Number.
If you want to use a generic type class like T you need to explicitly declare it in your class. Here you can find official documentation.
If you want to use an unknownk wildcard class instead, you can use if freely in you code as mentiond here
Anyway, you can find a similar question here
generic class in java should look like this
/**
* Generic version of the Box class.
* @param <T> the type of the value being boxed
*/
public class Box<T> {
// T stands for "Type"
private T t;
public void set(T t) { this.t = t; }
public T get() { return t; }
}
so you can use something like ArrayList<T> arr = new ArrayList<T>()
source: https://docs.oracle.com/javase/tutorial/java/generics/types.html