Java - How to create and initialize a List ArrayList in efficient way

Mar 23, 2016

Here are some better way to Create and initialize a ArrayList or List in Java. These are convenient methods if you want to initialize the list with fixed set of elements.

The traditional way to create list is

List<String> colors = new ArrayList<String>();

Below are few Methods to create and initialize the List

Method 1: Creating a List with one element in one line

If you want a list with only one element, then this is probably best way to create a list. List created by this way is immutable. That means we can not add more elements to this colors list

List<String> colors = Collections.singletonList("Red");

Method 2: Create and initialize a List in one line with multiple elements

List<String> colors = Arrays.asList("Red", "Green", "Blue");

This can create and initialize the List in one line but has got some limitations again. This list colors is immutable. if you will add/delete any additional element to this list, this will throw java.lang.UnsupportedOperationException exception. 

Method 3: Create and initialize a mutable List in one line with multiple elements

List<String> colors = new ArrayList<String>(Arrays.asList("Red", "Green", "Blue"));

This will create a mutable list which means further modification (addition, removal) to the is allowed.

Method 4: Mutable List with multiple element using Collections class

List<String> colors = new ArrayList<String>();

Method 5: Using anonymous inner class

List<String> colors = new ArrayList<String>() {{

comments powered by Disqus

© Copyright 2017