Java double bracket initialization operation tips

  • 2020-04-01 04:30:20
  • OfStack

Since the collections framework of the Java language (collections, such as list, map, set, and so on) does not provide any handy syntax structure, this makes the work of establishing a constant collection very complicated. Every time we set up, we do:

Define a temporary collection class variable create an instance of an empty collection, assign a value to the variable put the data into the collection and then pass the collection as an argument to the method

For example, to pass a Set variable to a method:


Set validCodes = new HashSet();
validCodes.add("XZ13s");
validCodes.add("AB21/X");
validCodes.add("YYLEX");
validCodes.add("AR2D");
removeProductsWithCodeIn(validCodes);

You can also use the static initialization method


private static final Set validCodes = new HashSet();
static {
validCodes.add("XZ13s");
validCodes.add("AB21/X");
validCodes.add("YYLEX");
validCodes.add("AR2D");
}
private static final Set validCodes = new HashSet();
static {
validCodes.add("XZ13s");
validCodes.add("AB21/X");
validCodes.add("YYLEX");
validCodes.add("AR2D");
}

In fact, there is a way to simplify the knot, we can use the double-brace syntax to create and initialize a new set:


private static final Set VALID_CODES = new HashSet() {{
add("XZ13s");
add("AB21/X");
add("YYLEX");
add("AR2D");
}};
private static final Set VALID_CODES = new HashSet() {{
add("XZ13s");
add("AB21/X");
add("YYLEX");
add("AR2D");
}};

or


removeProductsWithCodeIn(new HashSet() {{
add("XZ13s");
add("AB21/X");
add("YYLEX");
add("AR5E");
}});
removeProductsWithCodeIn(new HashSet() {{
add("XZ13s");
add("AB21/X");
add("YYLEX");
add("AR5E");
}});

The first bracket actually defines an Anonymous Inner Class, and the second bracket is actually an instance initializer block, which is executed when the Inner Anonymous Class is constructed. The blocks are called "instance initializer blocks" because they are defined within the instance scope of a class. This is different from a "static initialzer" in that it is defined with the static keyword in the bracket, so it is in the same scope as the class, meaning that it is executed when the class is loaded

All methods and variables within the instance initialization block can be used, but it is important to note that the instance initialization block is run before the constructor.

This works only for classes that are not final, because final classes cannot be subclassed internally anonymously, and fortunately collection classes do not have this limitation. Therefore, this method can also be used to initialize any other object, such as a GUI object:


add(new JPanel() {{
setLayout(...);
setBorder(...);
add(new JLabel(...));
add(new JSpinner(...));
}});
add(new JPanel() {{
setLayout(...);
setBorder(...);
add(new JLabel(...));
add(new JSpinner(...));
}});

This creates an instance of an inner anonymous class that contains a container reference to the image. If serialization, this collection also serializes its inner classes.

In addition, this double-bracket initialization can save a lot of code for map initialization, see:              


 Map<String, Set<String>> baselineMap = new HashMap<>();
      final String schema = "schema";
      if (baselineMap.get(type) == null) {
        baselineMap.put(type, new HashSet<String>() {{
          add(schema);
        }});
      } else {
        baselineMap.put(type, new HashSet<String>(baselineMap.get(type)) {{
          add(schema);
        }});
      }

I believe this code can be understood without any special explanation. Just think about how many more lines of code you would need to write if you didn't initialize it with double brackets! ~

The above is the Java double bracket initialization technique, which improves the readability of the code and simplifies the amount of code that you can try to apply to your own projects.


Related articles: