Also said Java's double-parenthesis initialization: In fact, is the inexplicable irregular code

Source: Internet
Author: User
Tags anonymous event listener

First look at the Cgaolei translation of the Java skills of the double bracket initialization of a text, a glance, only know usage, did not look at the explanation behind. Stunning, I think Java unexpectedly has such a magical grammar and has not been known. Because it is really convenient to initialize the collection. It turns out that some tests to initialize the collection will use the Commons-lang package and JDK's Arrays tool class, and now you know it:

01.Map map = new HashMap() {{
02.        put("Name", "Unmi");
03.        put("QQ", "1125535");
04.}};
05.
06.List stooges = new ArrayList() {{
07.        add("Larry");
08.        add("Moe");
09.        add("Curly");
10.}};

It all seems to be done in one statement without the need for a step-by-step write:

1.Map map = new HashMap();
2.map.put("Name","Unmi");
3.map.put("QQ","1125535");

Carelessly don't understand the person may think it is what special grammar, the key is the braces even a piece, the original author is also in the guise of posturing, beauty its name Yue: double bracket Grammar (double-brace syntax). is really disorderly flower gradually wants the attractive eye, actually is the anonymous class to add the initial block. This article explains: The first bracket actually defines an internal anonymous class (Anonymous Inner Class), and the second bracket is actually an instance initialization block (instance initializer block), which is executed when the internal anonymous class is constructed.

So how do you understand it better? It would be a better idea if we wrote the following, and the trick is to press Ctrl + Shift + F for the first piece of code in Eclipse as follows:

1.Map map = new HashMap() {
2.    {
3.        put("Name", "Unmi");
4.        put("QQ", "1125535");
5.    }
6.};

The anonymous class, in fact, creates a subclass of HashMap, an initialization block enclosed in an anonymous class of {}, which naturally places initialization code. The code in the {} block is compiled and placed in the <init> (), which is the constructor method, so it can be used to initialize the instance. If it is written in the Testdoublebrace class, you will see that the Testdoublebrace$1.class file is generated after compiling, and the contents of the decompile file are:

01.final class com.unmi.TestDoubleBrace$1 extends java.util.HashMap{ //创建了一个 HashMap 的子类 TestDoubleBracke$1
02.com.unmi.TestDoubleBrace$1();
03.  Code:
04.   0:   aload_0
05.   1:   invokespecial   #8; //Method java/util/HashMap."<init>":()V   //{} 中的代码放到了构造方法中去了
06.   4:   aload_0
07.   5:   ldc     #10; //String Name
08.   7:   ldc     #12; //String Unmi
09.   9:   invokevirtual   #14; //Method put:(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
10.   12:  pop
11.   13:  aload_0
12.   14:  ldc     #18; //String QQ
13.   16:  ldc     #20; //String 1125535
14.   18:  invokevirtual   #14; //Method put:(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
15.   21:  pop
16.   22:  return
17.
18.}

So frankly speaking, what double bracket grammar, is the code is not standardized, only to make so puzzling. If you don't understand, then list two more idiomatic code:

01.JFrame frame = new JFrame();
02.frame.addMouseListener(new MouseAdapter() {
03.    public void mouseClicked(MouseEvent e) {
04.        // do womething here.
05.    }
06.});
07.
08.Thread thread = new Thread() {{ // 也学着样把大括号也连一块写了
09.        this.setName("作业处理线程");
10.    }// 如果不重新定义 run() 方法,那么后面那个大括号也能与这个并一块
11.
12.    public void run() {
13.        // do something here.
14.    }
15.};
16.thread.start();

Should be no problem, the above is the event listener and multithreading commonly used to write, if he does not link braces together, but the specification of the code, I believe you will not at the beginning of the so-called Double brace Syntax have too much confusion. It's easy to say that this initialization method applies to the collection, but it's just a few more anonymous classes.

In the beginning, I saw this double notation as the Bible, only a smattering of it, yesterday in the use of XStream an object to generate an XML file, which has a List attribute, I borrowed this Fuffali initialization element, the result of the resulting XML file walked like, because of XStream Converter can handle ArrayList, but it is not good to handle the generated ArrayList anonymous subclasses. That's why we're looking back seriously at this so-called double-parenthesis initialization syntax.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.