How to initialize a list when declaring it

With array, we can easily declare and initialize it at the same time:

String[] favorites = new String[] {"EJB", "JPA", "GlassFish"};
Or even simpler:
String[] favorites = {"EJB", "JPA", "GlassFish"};
We can do the same with a List using java.util.Arrays.asList method. For example:
package javahowto;

import java.util.Arrays;
import java.util.List;

public class ListTest {
public static final List<String> favorites =
Arrays.asList("EJB", "JPA", "GlassFish");

public static void main(String[] args){
System.out.println("favorites: " + favorites);


Robert J Miller said...


CrAzYCakes said...

Why thanks!was looking for this

Jagat said...

Arrays.asList returns an immutable list. So you can't add any element to the list later.

Karola said...

Thanks, just what I needed to check against a list of constants.

Reece said...

Thank you, this is quite a good little gem I wasn't aware of!

Brian said...

Arrays.asList returns an immutable list. So you can't add any element to the list later.

While this is true, you can also pass the result of Arrays.asList() to the ArrayList constructor (or any other classes constructor that implements List). For example:

public static final List<String> favorites = new ArrayList<String>(Arrays.asList("EJB", "JPA", "Glassfish", "NetBeans"));


Justin said...

Thanks for explaining it very well

Anonymous said...




Daniel said...

Thank you!

Anna said...

Great and Useful Article.

Online Java Course

Java Online Training

Java Course Online

J2EE training

online J2EE training

Best Recommended books for Spring framework

Java Interview Questions

Java Training Institutes in Chennai

Java Training in Chennai

J2EE Training in Chennai

java j2ee training institutes in chennai

Vũ Diệu Linh said...

I enjoyed on reading your blog post. Very interesting to read this article.I would like to thank you for the efforts you had made for writing this awesome article. Please visit my website, Friv 4000 Games is where all the free friv games.
Friv 4000

eMexo Technologies said...

Good Post! Thank you so much for sharing this pretty post, it was so good to read and useful to improve my knowledge as updated one, keep blogging.

Dot net training in electronic city