Initializing ArrayList with some predefined values

Java

Java Problem Overview


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?

Java Solutions


Solution 1 - Java

try this

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

or

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

ARRAYS

Solution 2 - Java

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.

Solution 3 - Java

How about using overloaded ArrayList constructor.

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

Solution 4 - Java

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

Solution 5 - Java

import com.google.common.collect.Lists;

...


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

...

Solution 6 - Java

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

Solution 7 - Java

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

Solution 8 - Java

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]

Solution 9 - Java

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.

Solution 10 - Java

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

Solution 11 - Java

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

Solution 12 - Java

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

Solution 13 - Java

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

}    
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPawanView Question on Stackoverflow
Solution 1 - JavasambaView Answer on Stackoverflow
Solution 2 - JavaReimeusView Answer on Stackoverflow
Solution 3 - JavaPermGenErrorView Answer on Stackoverflow
Solution 4 - JavaDilum RanatungaView Answer on Stackoverflow
Solution 5 - JavaKristy HughesView Answer on Stackoverflow
Solution 6 - JavaGeorgios SyngouroglouView Answer on Stackoverflow
Solution 7 - JavaNarendra SorathiyaView Answer on Stackoverflow
Solution 8 - JavaJ-AlexView Answer on Stackoverflow
Solution 9 - JavamkiView Answer on Stackoverflow
Solution 10 - JavaZachFView Answer on Stackoverflow
Solution 11 - JavaManoj KumarView Answer on Stackoverflow
Solution 12 - JavaDomenico VacchianoView Answer on Stackoverflow
Solution 13 - JavaHimanshu ChaudharyView Answer on Stackoverflow