Generics
26 questions in 9 subtopics.
Type parameters and generic methods
Why doesList<Object> objs = new ArrayList<String>(); not compile, while Object[] arr = new String[1]; does?Write a generic method that returns the first element of any list or a default value, and a generic class Pair<A, B>. Explain where the type parameter is declared in each case.Your team's repository layer has methods like Object find(String type, Object id) with casts at every call site. Design a generic, type-safe alternative and explain the trade-offs.Over twenty years your organization's codebases have mixed raw types, unchecked casts and generic APIs. How would you raise type safety across hundreds of repositories without stopping delivery?Bounded type parameters
Write a method that returns the maximum of a collection of comparable elements. Why does the JDK'sCollections.max declare <T extends Object & Comparable<? super T>>?Explain how bounds affect what you can do inside a generic method, using <T extends Number> double sum(List<T> xs) versus double sum(List<? extends Number> xs). When do you need the type parameter?Wildcards and PECS
Explain PECS with the signature ofCollections.copy, and say which of these compile:List<? extends Number> a = new ArrayList<Integer>();
a.add(1);
List<? super Integer> b = new ArrayList<Number>();
b.add(1);
Integer x = b.get(0);
static void swapFirstTwo(List<?> list) { list.set(0, list.get(1)); }. Explain the error and fix it with wildcard capture.A method declared as void addAll(List<Number> target, List<Integer> source) cannot be called with a List<Object> target or a List<Integer> target. Rewrite the signature to be as flexible as possible.You are reviewing a shared library's public API with signatures such as void process(List<Event> events) and List<? extends Event> fetch(). What wildcard guidelines would you apply?Generic signatures in shared libraries are permanent once published, and badly chosen ones spread through every caller. What review process and rules would you set for generic APIs in your organization's libraries?Type erasure
What is type erasure? Give three things you cannot do because of it.If generics are erased, how do frameworks like Jackson, Spring and Hibernate learn that a field isList<Order>? Explain the reflection APIs and their limits.Java chose erasure for generics in Java 5 while C# chose reified generics. Explain why, what it has cost the platform over two decades, and how Project Valhalla is addressing parts of it.Bridge methods
Givenclass Name implements Comparable<Name> { public int compareTo(Name o) {...} }, what bridge method does javac generate and why? How can bridge methods appear in stack traces or reflection?A framework that scans methods by reflection registers each handler twice, or applies annotations inconsistently, for classes implementing generic interfaces. What is the cause and how do you fix the framework?Reifiable types and generic arrays
This code compiles with a warning and throwsClassCastException at the call site, not inside the method. Why?static <T> T[] toArray(List<T> list) {
return (T[]) list.toArray();
}
String[] s = toArray(List.of("a"));
new List<String>[10] illegal and how do you work around the need for a generic array, as ArrayList does internally?If Project Valhalla delivers value classes and later generic specialisation, collections of values could avoid boxing. How would you prepare a large codebase's generic APIs and data types today without depending on unfinished features?Heap pollution and @SafeVarargs
What is heap pollution, how do generic varargs cause it, and when is it safe to annotate a method with@SafeVarargs?Your codebase has thousands of @SuppressWarnings("unchecked") annotations and several heap pollution incidents. What policy and tooling do you introduce?Recursive generics
Explain the declarationabstract class Enum<E extends Enum<E>> implements Comparable<E>. What does the recursive bound guarantee?Design a fluent builder hierarchy for a base Request and a subclass HttpRequest using recursive generics, and discuss whether this complexity is worth it for a shared library.Type inference
Which lines compile and what types are inferred?List<String> a = new ArrayList<>();
var b = new ArrayList<>();
List<String> c = Collections.emptyList();
var d = List.of(1, 2.0);
Comparator<User> c = Comparator.comparing(u -> u.getName()); // ok
Comparator<User> d = Comparator.comparing(u -> u.getName()).reversed(); // error
No question matches these choices.