how to initialize static ArrayList in one line

后端 未结 6 430
醉话见心
醉话见心 2020-12-24 12:50

i have MyClass as

MyClass(String, String, int);

i know about how to add to add to ArrayList in this way:

MyClass.name = \"N         


        
6条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-24 13:18

    You can use double braces initialization: -

    List list = new ArrayList() {
        {
            add(new MyClass("name", "address", 23));
            add(new MyClass("name2", "address2", 45));
        }
    };
    

    As you can see that, inner braces is just like an initializer block, which is used to initialize the list in one go..

    Also note the semi-colon at the end of your double-braces

提交回复
热议问题