Java Double Brace Initialization – Java双括号初始化

最后修改: 2017年 5月 14日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

In this quick tutorial, we’ll show how double braces can be used for creating and initializing objects in a single Java expression.

在这个快速教程中,我们将展示如何使用双大括号在单个Java表达式中创建和初始化对象

We’ll also look at why this technique can be considered an anti-pattern.

我们还将看看为什么这种技术可以被认为是一种反模式。

2. Standard Approach

2.标准方法

Normally we initialize and populate a set of countries as follows:

通常情况下,我们初始化和填充一组国家,如下所示。

@Test
public void whenInitializeSetWithoutDoubleBraces_containsElements() {
    Set<String> countries = new HashSet<String>();                
    countries.add("India");
    countries.add("USSR");
    countries.add("USA");
 
    assertTrue(countries.contains("India"));
}

As can be seen from above example, we are doing the following:

从上面的例子可以看出,我们正在做以下工作。

  1. Create an instance of HashSet
  2. Add countries to the HashSet
  3. Finally, we assert whether the country is present in the HashSet

3. Using Double Brace

3.使用双撑杆

However, we can actually combine the creation and initialization in a single statement; this is where we make use of double braces:

然而,我们实际上可以将创建和初始化结合在一条语句中;这就是我们使用双括号的地方。

@Test
public void whenInitializeSetWithDoubleBraces_containsElements() {
    Set<String> countries = new HashSet<String>() {
        {
           add("India");
           add("USSR");
           add("USA");
        }
    };
 
    assertTrue(countries.contains("India"));
}

As can be seen from above example, we are:

从上面的例子可以看出,我们是。

  1. Creating an anonymous inner class which extends HashSet
  2. Providing an instance initialization block which invokes the add method and adds the country name to the HashSet
  3. Finally, we can assert whether the country is present in the HashSet

4. Advantages of Using Double Braces

4.使用双支架的优势

There are some simple advantages of using double braces:

使用双支架有一些简单的优势。

  • Fewer lines of code compared to the native way of creation and initialisation
  • The code is more readable
  • Creation initialization is done in the same expression

5. Disadvantages of Using Double Braces

5.使用双支架的弊端

Disadvantages of using double braces are:

使用双支架的缺点是。

  • Obscure, not widely known way to do the initialization
  • It creates an extra class every time we use it
  • Doesn’t support the use of the “diamond operator” – a feature introduced in Java 7
  • Doesn’t work if the class we are trying to extend is marked final
  • Holds a hidden reference to the enclosing instance, which may cause memory leaks

It’s due to these disadvantages that double brace initialization is considered as an anti-pattern.

正是由于这些缺点,双括号初始化被认为是一种反模式。

6. Alternatives

6.替代品

6.1. Stream Factory Methods

6.1.流工厂方法

Instead, we can make good use of the new Java 8 Stream API to initialize our Set:

相反,我们可以好好利用新的Java 8 Stream API来初始化我们的Set

@Test
public void whenInitializeUnmodifiableSetWithDoubleBrace_containsElements() {
    Set<String> countries = Stream.of("India", "USSR", "USA")
      .collect(collectingAndThen(toSet(), Collections::unmodifiableSet));
 
    assertTrue(countries.contains("India"));
}

6.2. Java 9 Collections Factory Methods

6.2.Java 9集合工厂方法

Also, Java 9 will bring a set of useful factory methods that will make the following possible:

另外,Java 9将带来一套有用的工厂方法,使以下情况成为可能。

List<String> list = List.of("India", "USSR", "USA");
Set<String> set = Set.of("India", "USSR", "USA");

You can read more about this in this article.

你可以在这篇文章中阅读更多关于这个的内容

7. Conclusion

7.结论

In this concise tutorial, we discussed the usage of double braces along with its advantages and disadvantages.

在这个简明的教程中,我们讨论了双大括号的用法以及它的优点和缺点。

The implementation of these examples can be found in the GitHub project – this is a Maven-based project, so it should be easy to import and run as-is.

这些例子的实现可以在GitHub项目中找到–这是一个基于Maven的项目,所以应该很容易导入并按原样运行。