Java Generic
- taolius
- Feb 8, 2016
- 1 min read
It's important to note that List<Object> and List<?> are not the same. You can insert an Object, or any subtype of Object, into a List<Object>. But you can only insert null into a List<?>.
The term List<Integer> is more restrictive than List<? super Integer> because the former matches a list of type Integer only, whereas the latter matches a list of any type that is a supertype of Integer.
The term List<Number> is more restrictive than List<? extends Number> because the former matches a list of type Number only, whereas the latter matches a list of type Number or any of its subclasses.
If the compiler erases all type parameters at compile time, why should you use generics? Answer: You should use generics because:
The Java compiler enforces tighter type checks on generic code at compile time.
Generics support programming types as parameters.
Generics enable you to implement generic algorithms.
Comentarios