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.
Code
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
URL Safety CheckerEvaluate a URL against common phishing red flags such as plain HTTP, embedded credentials, IP hosts, Punycode, and risky top-level domains.Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.bcrypt Cost EstimatorEstimate bcrypt cost factor latency and brute-force resistance, and get a recommended cost for your target hash time and attacker throughput.CORS Header Policy DebuggerSimulate browser CORS preflight and credential policies against server response headers to pinpoint blocked origins, methods, or headers and fix them.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.