how to initialize static ArrayList in one line

后端 未结 6 398
醉话见心
醉话见心 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:20

    The "best" way to do this in an effective way would be to :

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

    although it requires a lot of typing but as you can clearly see this is more efficient

    Another alternative would be to use google guava (not tested for efficiency):

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

    The required import is import static com.google.common.collect.Lists.newArrayList;

    also, you can use double braces initialization as originally proposed by @Rohit Jain: -

    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..

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

    also note the last method has some downsides as discussed here.

提交回复
热议问题