Generics Flashcards
What is Type erasure?
Process of converting generics to Objects
Static and generics?
Not permitted. static T
Primitives and generics?
Not permitted. < int >
Instantiating a generic?
Not permitted. new T()
Checking instanceof a generic?
Not permitted.
Using generic in ArrayList?
Not permitted. new ArrayList< T >
What generics actually become after compile?
Object
What types of wildcard generics do we have?
Unbounded, upper bounded, lower bounded
What are unbound generics?
<?>
Can we pass multiple generics?
Yes. <T, U>
Can wildcard generics be used as return types?
No
Where do we use wildcard generics?
Mostly as parameters or as local variable types
Why would we use wildcard generics?
To define code that can be more universal
At what level are generics resolved?
At instance level
Why cannot we use generics with static?
Because static is resolved at class level, not instance level like generics
Where can static be used with generics?
On static methods with < T >
What does “public static < T >T identity(T t)” mean?
It is a method of name “identity”, where we use type parameter < T >, which defines return type T and method parameter T.
What does “public static T noGood(T t)” mean?
No good. Compile error, since we dont tell compiler that we want to use generic type. We define object T as return type, and object T as parameter type.
What does “public static < T > void sink(T t)” mean?
Method that has no return type, but we define type parameter < T > for method parameter T t
Where can T be used at?
As member types, as parameter argument types, as method parameter types
In what types of classes can generics be used?
In classes, records, interfaces
Can wildcard generics be used with generic types?
Yes. <? extends T>
Can we use upper and lower bounds on generic types?
Yes. < T extends SomeClass >
Where can we use upper and lower bound generic types?
At same places (reference types) where we can use generic types
When to use “<? extends T>”
When we want to make collection read only
When to use <? super T> (lower bound wildcard)
When we want to make collection write only
What should we watch out regarding generics and method parameters?
Watch for overloading problems - eg. List< T > becomes List< Object >, so we cannot have two methods with those in same signature
What should we watch out regarding generics and return types when overriding?
Return type must be covariant, so watch out when overriding methods with generics
Why “lower bound wildcard” as name, or “upper bound wildcard”?
Wildcard can be any class.
Bound means depicts that something linked or depends on something.
Regarding lower or upper, imagine class diagrams.
Lower bound, or super, is drawn from down to up in hierarchy.
Upper bound, or extends, is drawn from up to down.
Can wildcards be used when instantianting objects?
No, Java requires to be type specific. References can use wildcards tho.