Double‑Brace Initialization in Java Collections: Pitfalls and Safer Alternatives
The article explains how double‑brace syntax creates anonymous inner classes for initializing Java collections, discusses the hidden overhead and memory‑leak risks it introduces, and presents cleaner alternatives such as Arrays.asList, Stream.of, Guava immutable factories, and Java 9's of‑methods.
Java's collection framework lacks concise syntax for initializing constant collections, leading developers to use verbose code.
The article introduces the double‑brace syntax, which creates an anonymous inner class to initialize a Set or Map, showing example code.
Set users = new HashSet() {{ add("Hollis"); add("hollis"); add("HollisChuang"); add("hollis666"); }};Compiling such code generates additional class files (e.g., DoubleBraceTest$1.class), indicating the creation of anonymous inner classes that increase class‑loader overhead and can retain references that hinder garbage collection.
Returning a map built with double‑brace initialization may unintentionally hold a reference to the enclosing instance, causing memory‑leak risks.
Therefore, the article recommends safer alternatives: using Arrays.asList(...) for lists, Stream.of(...).collect(Collectors.toList()) , third‑party utilities like Guava's ImmutableMap.of(...) , and Java 9's List.of(...) and Map.of(...) methods.
These approaches avoid the hidden anonymous class creation and provide immutable or more efficient collection initialization.
Full-Stack Internet Architecture
Introducing full-stack Internet architecture technologies centered on Java
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.