Generics, Type Erasure and Wildcards
40 min · Intermediate
Generics let a class or method work with a type parameter such as T, so the compiler checks types for you and you never cast. Interview questions focus on the parts that surprise people: type erasure, wildcards and why a List<Integer> cannot be passed where a List<Number> is expected.
Topics in this lesson
- Why generics: type safety and no casts
- Type erasure: what remains at runtime
- Wildcards: ? extends vs ? super and PECS
- Why List<Integer> is not a List<Number>
- Writing a generic method with a bounded type
Interview questions this lesson answers
- What are generics and why were they added?
- What is a raw type?
- What is type erasure?
- Why did Java choose type erasure?
- Why can you not write new T()?
- Why can you not create a generic array like new T[10]?
- Why is List<int> not allowed?
- Can you overload methods that differ only in generic type arguments?
- Can you use instanceof with a generic type?
- What is the difference between List<?> and List<Object>?
Sign in free to continue this lesson
Create a free account to read every lesson, practise with the exercises and keep track of your progress.