ExerciseWarm-up
Warm-up
Two lists, one class
5 minjunior1–5 yrs
One concept, guided. Near-impossible to fail.
What this teaches
- A type argument is a compile-time promise, not a runtime type
- getClass() returns the same object for List<String> and List<Integer>
- instanceof against a type argument does not compile, and the error says why
Starter
Starter.javaOpen in playground
import java.util.*;
/**
* WARM-UP — 5 minutes. One concept. Hard to fail.
*
* Two lists that the compiler treats as completely different types.
* The runtime has a different opinion.
*
* TASKS
* 1. Write down your prediction for every println BEFORE running.
* 2. Run it.
* 3. Uncomment the line marked (3). Read the compiler error carefully —
* it tells you exactly what the JVM cannot do. Then comment it back.
* 4. Line (4) compiles. Explain in a comment why `List<?>` is answerable
* when `List<String>` is not.
*/
public class Starter {
public static void main(String[] args) {
List<String> names = new ArrayList<>();
List<Integer> scores = new ArrayList<>();
System.out.println("names class : " + names.getClass().getName());
System.out.println("scores class : " + scores.getClass().getName());
System.out.println("same class : " + (names.getClass() == scores.getClass()));
System.out.println("equal lists : " + names.equals(scores));
Object mystery = names;
// (3) Uncomment this one line. It will not compile.
// System.out.println("is it strings : " + (mystery instanceof List<String>));
// (4) This one does compile. Why?
System.out.println("is it a list : " + (mystery instanceof List<?>));
// Question to answer in a comment before you move on:
// `names` was declared to hold Strings. At runtime, where is that
// information? Name one place in the class file it still exists.
}
}Run it locally:
cd exercises/java/generics/type-erasure/01-warmup
javac Starter.java -d /tmp/out && java -cp /tmp/out StarterDone when
- You predicted each line before running it
- The instanceof line is uncommented, read, and then commented back out
- A comment explains why List<?> is allowed where List<String> is not