Generics & Type Inference Flashcards
7 cards from real 1Z0-819 practice questions. Tap to flip, then mark Knew It or Still Learning — missed cards come back until you master them.
Read the first 7 Generics & Type Inference flashcards as text
What is the PECS principle in Java generics?
Answer: Producer Extends, Consumer Super
PECS stands for Producer Extends, Consumer Super: use when reading (producing) from a structure, and when writing (consuming) to a structure.
Which operation is valid on a variable declared as List?
Answer: Reading elements and treating them as Number type
With an upper-bounded wildcard , you can read elements as Number or its supertype, but cannot add any elements because the exact subtype is unknown to the compiler.
Which operation is valid on a variable declared as List?
Answer: Adding an Integer or any of its subtypes to the list
With a lower-bounded wildcard , you can safely add Integer values (or subtypes) to the list, but reading only returns Object.
Which of the following correctly declares a type parameter with multiple bounds?
Answer: public class MyClass>
Multiple bounds use the & separator between bounds, and all bounds must use the extends keyword — even for interfaces — as in >.
Why does the following code NOT compile? List nums = new ArrayList();
Answer: Generic types in Java are invariant, so List is not a subtype of List
Java generics are invariant, meaning List is not a subtype of List even though Integer is a subtype of Number; this prevents heap pollution.
What is the correct signature for Collections.sort() that handles types comparable to their supertypes?
Answer: public static > void sort(List list)
Collections.sort() uses > to allow types whose compareTo method accepts a supertype, making it more flexible than the simpler >.
What is the result of calling getClass() on a List and a List at runtime?
Answer: They return the same class object because type erasure removes parameterized type information
Due to type erasure, both List and List share the same runtime class (e.g., java.util.ArrayList), so getClass() returns the same Class object.