The Collection framework of Java language (collections, such as list, map, set, etc.) does not provide any simple syntax structure, which makes it very complicated to create a constant set. We need to do this each time we create:
Define a temporary collection class variable
Create an instance with an empty set and assign it to the variable
Put data into a collection
Finally, pass the set as a parameter to the method.
For example, to pass a Set variable to a method:
Set <String> validCodes = new HashSet <String> ();
ValidCodes. add ("XZ13s ");
ValidCodes. add ("AB21/X ");
ValidCodes. add ("YYLEX ");
ValidCodes. add ("AR2D ");
RemoveProductsWithCodeIn (validCodes );
You can also use the static initial method.
Private static final Set <String> validCodes = new HashSet <String> ();
Static {
ValidCodes. add ("XZ13s ");
ValidCodes. add ("AB21/X ");
ValidCodes. add ("YYLEX ");
ValidCodes. add ("AR2D ");
}
In fact, there are also simple methods. We can use double-brace syntax to create and initialize a new set:
Private static final Set <String> VALID_CODES = new HashSet <String> (){{
Add ("XZ13s ");
Add ("AB21/X ");
Add ("YYLEX ");
Add ("AR2D ");
}};
Or
RemoveProductsWithCodeIn (new HashSet <String> (){{
Add ("XZ13s ");
Add ("AB21/X ");
Add ("YYLEX ");
Add ("AR5E ");
}});
The first layer of the arc defines an internal Anonymous Class (Anonymous Inner Class). The second layer of the arc is actually an instance initialization block (instance initializer block ), this block is executed during internal Anonymous class construction. This block is called "instance initialization block" because it is defined within the instance range of a class. This is different from "static initialzer", because this type of block uses the static keyword before the arc during definition, so it and the class are in the same scope, that is, the class will be executed when it is loaded (for more details, refer to the Java language specification http://java.sun.com/docs/books/jls/third_edition/html/classes.html#8.6 ). All methods and variables within the container range can be used in the instance initialization block, but note that the instance initialization block runs before the constructor.
This method applies only to classes that are not final, because the final class cannot create an internal anonymous subclass. Fortunately, this restriction is not applied to the Collection class. 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 (...));
}});
In this way, the internal Anonymous class instance is provided with its container reference to the image. If serialization is set, its external classes are serialized.
Author: "Zuo Luo CTO"