Java{{}} writing method, anonymous inner class initialization

foreword

When I was brushing the questions, I saw that someone wrote the code and used { {}}the wording method. I have never seen it before, so I hereby record it.

 Queue<TreeNode> queue = new LinkedList<>() {
    
    {
    
     add(root); }};

a brief introdction

example

{ {}}This method is to initialize a collection, avoiding adding one by one to the collection initialization.

ArrayList<String> list = new ArrayList<String>(){
    
    
{
    
    
	add("A");
	add("B");
	add("C");
}};
// 和下面功能实现一样
//        ArrayList<String> list = new ArrayList<String>();
//        list.add("a");
//        list.add("b");
//        list.add("c");

understand

first bracket

//定义了一个继承于ArrayList的类,它没有名字
new ArrayList<String>(){
    
    
  //在这里对这个类进行具体定义
};

The brackets here represent a specific definition of a class.

second parenthesis


new ArrayList<String>(){
    
    
  {
    
    
    //这里是实例初始化块,可以直接调用父类的非私有方法或访问非私有成员
  }
};

The brackets here indicate the instance initialization block (Instance Initialiazer Block), also known as the non-static initialization block.

Analogous to static initial block

static{
    
    
	//静态初始块
}

reference

https://www.cnblogs.com/dengyungao/p/7524981.html

Guess you like

Origin blog.csdn.net/qq_44850917/article/details/124711276