Checked Collections Reject Wrong Element Types

A raw alias can smuggle an Integer into a plain List<String>, which only explodes on read; Collections.checkedList throws the ClassCastException at the insert.

JavaSecurity Boundaries

Code

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

public class CheckedBoundary {

    public static void main(String[] args) {
        List<String> plain = new ArrayList<>();
        List<String> checked = Collections.checkedList(new ArrayList<>(), String.class);

        // 原始类型别名绕过编译期检查:错误元素静静入库
        List rawPlain = plain;
        rawPlain.add(42);
        System.out.println("plain insert accepted, size=" + plain.size());
        try {
            String first = plain.get(0);   // 泛型读取点才插入强制转换
            System.out.println("read: " + first);
        } catch (ClassCastException e) {
            System.out.println("plain read failed: " + e.getClass().getSimpleName());
        }

        // checked 视图把同样的别名插入挡在边界上
        List rawChecked = checked;
        try {
            rawChecked.add(42);
            System.out.println("checked insert accepted");
        } catch (ClassCastException e) {
            System.out.println("checked insert rejected: " + e.getClass().getSimpleName());
        }
        System.out.println("checked size=" + checked.size());
    }
}

How it works

The code’s whole job belongs to the class CheckedBoundary and the function main.

Watch out for

  • Every symbol it uses is a language built-in — nothing needs fetching.

Using it

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

Output lines are prefixed (plain insert accepted, size=, read:, plain read failed:), so each step’s effect shows up clearly in the output.

The key statements, annotated

List<String> checked = Collections.checkedList(new ArrayList<>(), String.class);
String first = plain.get(0);   // 泛型读取点才插入强制转换
System.out.println("read: " + first);
List<String> plain = new ArrayList<>();

Interactive Tools for This Topic

FAQ

What does Checked Collections Reject Wrong Element Types print when run?
No setup needed: run the file and look for labeled lines like `plain insert accepted, size=`, `read:`, `plain read failed:` in the output.