Dave's Brain

Browse - Programming Tips - How can I initialize an ArrayList of Strings in one statement?

Date: 2014nov3
Updated: 2016nov25
Language: Java
Keywords: init

Q.  How can I initialize an ArrayList of Strings in one statement?

A.  Use things in util.Arrays:

import java.util.Arrays; // One way ArrayList<String> colors = new ArrayList<String>(Arrays.asList("red", "green", "blue"));
// Another way ArrayList<String> colors = new ArrayList<String>(Arrays.asList(new String[] {"red", "green", "blue}));
// But if its constants you can just use a regular array static final String colors [] = { "red", "green", "blue" };

Add a comment

Sign in to add a comment
Copyright © 2008-2017, dave - Code samples on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License. However other material, including English text has all rights reserved.