Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing ArrayList with some predefined values [duplicate]

Tags:

java

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?

like image 822
Pawan Avatar asked Apr 24 '13 14:04

Pawan


People also ask

How do you initialize an ArrayList with multiple values?

To initialize an ArrayList with multiple items in a single line can be done by creating a List of items using Arrays. asList(), and passing the List to the ArrayList constructor. In the given example, we are adding two strings “a” and “b” to the ArrayList.

Can you initialize ArrayList with values?

Java developers use the Arrays. asList() method to initialize an ArrayList. Using asList() allows you to populate an array with a list of default values. This can be more efficient than using multiple add() statements to add a set of default values to an ArrayList.

How do you initialize all values of an ArrayList in Java?

To initialize an arraylist in single line statement, get all elements in form of array using Arrays. asList method and pass the array argument to ArrayList constructor. ArrayList<String> names = new ArrayList<String>( Arrays.


2 Answers

try this

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

or

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

ARRAYS

like image 80
samba Avatar answered Sep 18 '22 18:09

samba


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.

like image 36
Reimeus Avatar answered Sep 20 '22 18:09

Reimeus