81

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?

3
  • 2
    Add them in a Constructor. Commented Apr 24, 2013 at 14:41
  • 2
    Will this help? stackoverflow.com/questions/1005073/… Commented Apr 24, 2013 at 14:43
  • 1
    better fit for an enum here? Commented Apr 24, 2013 at 14:47

13 Answers 13

167

try this

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

or

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

ARRAYS

Sign up to request clarification or add additional context in comments.

4 Comments

good solution, asList(...) returns new ArrayList<>(a) like the question's author requested
@CarlosHenriqueRodriguez asList(...) returns List<E> not ArrayList<E>
@PermGenError List is the return type, the method returns ArrayList. It's not java.util.ArrayList, it's an internal class with the same behavior
The list returned by Arrays.asList(T...) is capped in size to the size of the array supplied in the constructor. That may or may not be an issue, depending on usage.
60

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.

7 Comments

interesting anonymous innterclass!
If you add an object that was defined outside of this structure, you'll need to declare it final in order for it to compile. Read this answer if you want to know why.
There's also a performance penalty, although it's significance is debatable.
this is cool, but in Java 7 you can avoid specifying the type in the initialization: here docs.oracle.com/javase/7/docs/technotes/guides/language/…
@Rose that link only details standard List initialization, i.e. no anonymous inner class with values being added :)
|
21

How about using overloaded ArrayList constructor.

 private ArrayList<String> symbolsPresent = new ArrayList<String>(Arrays.asList(new String[] {"One","Two","Three","Four"}));

4 Comments

wouldn't Arrays.asList() alone do the job?
@CarlosHenriqueRodriguez it would, but then you will have to have List<String> on the left side. :)
Note that you can use the var-args syntax with Java 5 and later.
If I am not mistaken, if you use Arrays.asList() and use directly the returned List, it would be fixed size. Basically it would still behave like an array, just wrapped in List interface.
13

You can also use the varargs syntax to make your code cleaner:

Use the overloaded constructor:

ArrayList<String> list = new ArrayList<String>(Arrays.asList("a", "b", "c"));

Subclass ArrayList in a utils module:

public class MyArrayList<T> extends ArrayList<T> {
    public MyArrayList(T... values) {
        super(Arrays.asList(values));
    }
}

ArrayList<String> list = new MyArrayList<String>("a", "b", "c");

Or have a static factory method (my preferred approach):

public class Utils {
  public static <T> ArrayList<T> asArrayList(T... values) {
    return new ArrayList<T>(Arrays.asList(values));
  }
}

ArrayList<String> list = Utils.asArrayList("a", "b", "c");

Comments

11
import com.google.common.collect.Lists;

...


ArrayList<String> getSymbolsPresent = Lists.newArrayList("item 1", "item 2");

...

Comments

9

You can use Java 8 Stream API.
You can create a Stream of objects and collect them as a List.

private List<String> symbolsPresent = Stream.of("ONE", "TWO", "THREE", "FOUR")
    .collect(Collectors.toList());

1 Comment

Voted up because streams provide a uniform mechanism for addressing a wide range of problems whereas the custom functions simply chew up mortal memory.
7
public static final List<String> permissions = new ArrayList<String>() {{
    add("public_profile");
    add("email");
    add("user_birthday");
    add("user_about_me");
    add("user_location");
    add("user_likes");
    add("user_posts");
}};

Comments

5

Java 9 allows you to create an unmodifiable list with a single line of code using List.of factory:

public class Main {
    public static void main(String[] args) {
        List<String> examples = List.of("one", "two", "three");
        System.out.println(examples);
    }
}

Output:

[one, two, three]

Comments

3

Personnaly I like to do all the initialisations in the constructor

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

Edit : It is a choice of course and others prefer to initialize in the declaration. Both are valid, I have choosen the constructor because all type of initialitions are possible there (if you need a loop or parameters, ...). However I initialize the constants in the declaration on the top on the source.
The most important is to follow a rule that you like and be consistent in our classes.

Comments

2

Also, if you want to enforce the List to be read-only (throws a UnsupportedOperationException if modified):

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

Comments

2

I would suggest to use Arrays.asList() for single line initialization. For different ways of declaring and initializing a List you can also refer Initialization of ArrayList in Java

Comments

1

I use a generic class that inherit from ArrayList and implement a constructor with a parameter with variable number or arguments :

public class MyArrayList<T> extends ArrayList<T> {
    public MyArrayList(T...items){
        for (T item : items) {
            this.add(item);
        }
    }
}

Example:

MyArrayList<String>myArrayList=new MyArrayList<String>("s1","s2","s2");

Comments

0

If you just want to initialize outside of any method then use the initializer blocks :

import java.util.ArrayList;

public class Test {
private ArrayList<String> symbolsPresent = new ArrayList<String>();

// All you need is this block.
{
symbolsPresent = new ArrayList<String>();
symbolsPresent.add("ONE");
symbolsPresent.add("TWO");
symbolsPresent.add("THREE");
symbolsPresent.add("FOUR");
}


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);

}    
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.