Collections: emptyList and singletonList are fixed-size, shared and cheap

Collections.emptyList() returns one shared immutable instance and singletonList holds exactly one element without a backing array; both reject add, which makes them safe defaults to return instead of null or a fresh ArrayList.

Code
List<String> none = Collections.emptyList();
List<String> again = Collections.emptyList();
System.out.println("Same shared instance: " + (none == again));
List<String> one = Collections.singletonList("admin");
System.out.println("Singleton: " + one + " size=" + one.size());
try {
    one.add("guest");
} catch (UnsupportedOperationException e) {
    System.out.println("add rejected: " + e.getClass().getSimpleName());
}
System.out.println("set on singleton: " + tryset(one));
static String tryset(List<String> l) {
    try { l.set(0, "root"); return "allowed -> " + l; }
    catch (UnsupportedOperationException e) { return "rejected"; }
}
Output
Same shared instance: true
Singleton: [admin] size=1
add rejected: UnsupportedOperationException
set on singleton: rejected
Advertisement
More in JAVA

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-09-27

© Java Coding Hub · About · Contact · Privacy · Terms