Double brace initialization in Java looks like magic until you realize it is just a tiny circus act with hidden costs. The pattern creates an anonymous inner class and then runs an instance initializer block to add elements to a collection. It is compact and satisfying to type which is why it shows up in examples and quick hacks.
List list = new ArrayList()
Yes it looks clever and terse. No it does not buy you any performance or safety. It just hides a subclass and a few surprises.
Under the hood you get an anonymous subclass of the collection class. The outer brace declares the subclass. The inner brace is an instance initializer that runs add calls when the object is created. That initializer is valid Java and behaves exactly like any other instance initializer block.
It is compact and reads like a literal. For tiny test data or throwaway examples where brevity matters more than robustness it can be tempting. It gives a quick literal like syntax for small collections which is why you see it in blog posts and snippets.
Use the standard factory and utility methods and save the cute patterns for blog posts. These are clear and predictable which is what you want in production.
List immutable = List.of("one", "two")
List mutable = new ArrayList<>(Arrays.asList("one", "two"))
List another = new ArrayList<>()
Collections.addAll(another, "one", "two")
If you run into it while reading older code look for an unexpected anonymous inner class. Ask whether serialization is involved and check for unintended outer class captures. If the code is not tiny test setup refactor to a factory or explicit construction.
Prefer explicit construction and factory methods for lists and sets in production. Use List.of for immutable small collections and use clear mutable constructors when you need to change the collection. Keep double brace initialization for toy examples and the parts of your life where consequences are limited.
Tip Keep your code predictable and your stack traces readable. Your future self will thank you or at least avoid a quiet, simmering grudge.
I know how you can get Azure Certified, Google Cloud Certified and AWS Certified. It's a cool certification exam simulator site called certificationexams.pro. Check it out, and tell them Cameron sent ya!
This is a dedicated watch page for a single video.