Over a million developers have joined DZone.

Java’s Arrays.asList(…) is underused

· Java Zone

Learn more about how the Java language, tools and frameworks have been the foundation of countless enterprise systems, brought to you in partnership with Salesforce.

Writing nice and concise code is feasible in Java as well, not only in those hyped, new, and fancy scripting languages. Here are some examples on how to use the Java 5 varargs Arrays.asList() method in nice contexts:

Run a block for n constant values

// If you have VAL_A, VAL_B, VAL_C and you want
// to execute something for every one of those values:
for (String value : Arrays.asList(VAL_A, VAL_B, VAL_C)) {

// Here's how you can create a SQL-like IN operator
// to check for existence in a "set"
if (Arrays.asList(VAL_A, VAL_B, VAL_C).contains(value)) {

// Of course, this would even be nicer to have, as
// syntactic sugar
if (value in [VAL_A, VAL_B, VAL_C]) {

The latest example is taken from one of my Stack Overflow questions:


And indeed, something like this is fathomable. There had been an old specification request by Josh Bloch, to support collection literals in Java:


Too bad it never made it into the JLS…


From http://lukaseder.wordpress.com/2011/10/28/javas-arrays-aslist-is-underused/

Discover how the Force.com Web Services Connector (WSC) is a code-generation tool and runtime library for use with Force.com Web services, brought to you in partnership with Salesforce.


The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}