What is Double Brace initialization syntax ({{ ... }}
) in Java?
As pointed out by @Lukas Eder double braces initialization of collections must be avoided.
It creates an anonymous inner class, and since all internal classes keep a reference to the parent instance it can - and 99% likely will - prevent garbage collection if these collection objects are referenced by more objects than just the declaring one.
Java 9 has introduced convenience methods List.of
, Set.of
, and Map.of
, which should be used instead. They're faster and more efficient than the double-brace initializer.