Home  >  Article  >  Java  >  Detailed explanation of Java initialization method classes and containers

Detailed explanation of Java initialization method classes and containers

迷茫
迷茫Original
2017-03-26 15:53:421986browse

Java initialization method: class, container

Initialization class (non-final):

In the DefaultActionMapper class of Struts2:

public DefaultActionMapper() {
    prefixTrie = new PrefixTrie() { {
        put(METHOD_PREFIX, new ParameterAction() {
            public void execute(String key, ActionMapping mapping) {
                if (allowDynamicMethodCalls) {
                    mapping.setMethod(key.substring( METHOD_PREFIX.length()));
                }
            }
         }); //。。。。
     }};
}

put is the method of PrefixTrie: public void put(String prefix, Object value) ;

Initialize container:

Original method in collection framework (collections, such as list, map, set, etc.):

Set<String> myset = new HashSet<String>();
myset.add("aa");
myset.add("bb");
myset.add("cc");
myset.add("dd");
domethod(myset);

Static initialization Method:

private static final Set<String> myset = new HashSet<String>();
static { myset.add("aa");
    myset.add("bb");
    myset.add("cc");
    myset.add("dd");
}

Double-brace syntax (double-brace syntax) creates and initializes a new collection:

private static final Set<String> myset = new HashSet<String>() {{
    add("aa");
    add("bb");
    add("cc");
    add("dd");
}};
doMethod(new HashSet<String>() {{
    add("aa");
    add("bb");
    add("cc");
    add("dd");
}});

First level of brackets It actually defines an internal anonymous class (Anonymous Inner Class);

The second layer of brackets is actually an instance initialization block ( instance initializer block), this block is executed during the construction of the inner anonymous class.

The above is the detailed content of Detailed explanation of Java initialization method classes and containers. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn