Initializing ArrayList with some predefined values

I have an sample program as shown.

I want my ArrayList symbolsPresent to be initialized with some predefined symbols: ONE, TWO, THREE, and FOUR.

symbolsPresent.add("ONE");
symbolsPresent.add("TWO");
symbolsPresent.add("THREE");
symbolsPresent.add("FOUR");

import java.util.ArrayList;

public class Test {

    private ArrayList<String> symbolsPresent = new ArrayList<String>();

    public ArrayList<String> getSymbolsPresent() {
        return symbolsPresent;
    }

    public void setSymbolsPresent(ArrayList<String> symbolsPresent) {
        this.symbolsPresent = symbolsPresent;
    }

    public static void main(String args[]) {    
        Test t = new Test();
        System.out.println("Symbols Present is" + t.symbolsPresent);

    }    
}

Is that possible?


try this

new String[] {"One","Two","Three","Four"};

or

List<String> places = Arrays.asList("One", "Two", "Three");

ARRAYS


Double brace initialization is an option:

List<String> symbolsPresent = new ArrayList<String>() {{
   add("ONE");
   add("TWO");
   add("THREE");
   add("FOUR");
}};

Note that the String generic type argument is necessary in the assigned expression as indicated by JLS §15.9

It is a compile-time error if a class instance creation expression declares an anonymous class using the "<>" form for the class's type arguments.


如何使用重载的ArrayList构造函数

 private ArrayList<String> symbolsPresent = new ArrayList<String>(Arrays.asList(new String[] {"One","Two","Three","Four"}));
链接地址: http://www.djcxy.com/p/82402.html

上一篇: Java ArrayList和HashMap在上

下一篇: 用一些预定义值初始化ArrayList