Type Erasure Same Runtime Class

Two ArrayLists with different type arguments share one runtime class: the raw add bypasses checks and the cast failure surfaces at the typed read-back.

JavaData Integrity

Code

snippet
import java.util.ArrayList;
import java.util.List;

public class ErasureIdentity {

    public static void main(String[] args) {
        List<String> strings = new ArrayList<>();
        List<Integer> numbers = new ArrayList<>();
        strings.add("ok");

        // 泛型只在编译期存在:不同类型参数的 ArrayList 是同一个运行时 Class
        System.out.println("same class: " + (strings.getClass() == numbers.getClass()));
        System.out.println("class name: " + strings.getClass().getName());
        System.out.println("type params erased: " + strings.getClass().getTypeParameters().length);

        // raw 类型绕过编译期检查:add 本身不报错,运行时只存引用、不校验元素类型
        List raw = strings;
        raw.add(42);

        // 读回先用 Object 接收:赋值目标为 Object 时编译器不插 checkcast,
        // 才能看到混入元素的真实运行时类型
        Object first = strings.get(0);
        Object second = strings.get(1);
        System.out.println("element types: " + first.getClass().getSimpleName()
                + ", " + second.getClass().getSimpleName());

        // 真正的失败点在按声明类型 String 取用:编译器在该读回点插入 checkcast
        try {
            String leaked = strings.get(1);
        } catch (ClassCastException e) {
            System.out.println("delayed failure: " + e);
        }
    }
}

Type Erasure Same Runtime Class: what runs and why

Under the hood: the class ErasureIdentity and the function main.

Watch out for

  • Copy, run: the standard library answers every call in the file.

Putting it to use

Signature: public static void main(String[] args)

The run prints these markers in turn: same class:, class name:, type params erased:.

Core lines

List<Integer> numbers = new ArrayList<>();
List<String> strings = new ArrayList<>();
Object second = strings.get(1);

Interactive Tools for This Topic

FAQ

What does Type Erasure Same Runtime Class print when run?
Invoke the file as-is — the `same class:`, `class name:`, `type params erased:` prefixes identify which step printed each line.