Java / Java 21 Interview Questions
What are the immutable collection factory methods introduced in Java 9?
Java 9 (JEP 269) introduced convenient static factory methods on List, Set, and Map for creating small, immutable collections without the verbosity of Arrays.asList() or Collections.unmodifiableList().
// Java 9+ — concise and immutable
List list = List.of("a", "b", "c"); // immutable
Set set = Set.of(1, 2, 3); // immutable, no dups
Map map = Map.of("one", 1, "two", 2); // up to 10 pairs
Map bigMap = Map.ofEntries( // more than 10 pairs
Map.entry("a", 1),
Map.entry("b", 2)
);
// Copying (Java 10+)
List copy = List.copyOf(mutableList); // immutable copy
Set sCopy = Set.copyOf(existingSet);
// Java 9 vs Arrays.asList
// Arrays.asList: fixed-size but MUTABLE (set() works, add() throws)
// List.of: IMMUTABLE (set(), add(), remove() all throw)
list.add("d"); // UnsupportedOperationException
list.set(0, "z"); // UnsupportedOperationException
// Null not permitted in List.of / Set.of / Map.of
List.of("a", null, "c"); // NullPointerException at creation
// Set.of does not allow duplicates
Set.of(1, 2, 2); // IllegalArgumentException These factory-created collections are optimised for memory: small sets and maps use compact array-based implementations rather than hash tables when they have few elements. The iteration order of Set.of and Map.of is intentionally unspecified and may vary between JVM runs.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
