3/11/2008

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

10 comments:

Robert J Miller said...

thanks!

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...

[quote=Jagat]
Arrays.asList returns an immutable list. So you can't add any element to the list later.
[/quote]

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:

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

[/code]

Justin said...

Thanks for explaining it very well

Anonymous said...

Arrays.asList()

Not

Array.asList()

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