Initialization of an ArrayList in one line

后端 未结 30 2773
北恋
北恋 2020-11-22 01:10

I wanted to create a list of options for testing purposes. At first, I did this:

ArrayList places = new ArrayList();
places.add(\         


        
30条回答
  •  庸人自扰
    2020-11-22 01:56

    The best way to do it:

    package main_package;
    
    import java.util.ArrayList;
    
    
    public class Stackkkk {
        public static void main(String[] args) {
            ArrayList list = new ArrayList();
            add(list, "1", "2", "3", "4", "5", "6");
            System.out.println("I added " + list.size() + " element in one line");
        }
    
        public static void add(ArrayList list,Object...objects){
            for(Object object:objects)
                list.add(object);
        }
    }
    
    
    

    Just create a function that can have as many elements as you want and call it to add them in one line.

    提交回复
    热议问题