What is Double Brace initialization in Java?

前端 未结 13 2289
旧时难觅i
旧时难觅i 2020-11-21 07:22

What is Double Brace initialization syntax ({{ ... }}) in Java?

13条回答
  •  野性不改
    2020-11-21 08:03

    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.

提交回复
热议问题