Initializing ArrayList with some predefined values

71

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?

This question is tagged with java

~ Asked on 2013-04-24 14:40:46

The Best Answer is


157

try this

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

or

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

ARRAYS

~ Answered on 2013-04-24 14:43:02


54

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.

~ Answered on 2013-04-24 14:48:38


Most Viewed Questions: