Over a million developers have joined DZone.

Java’s Arrays.asList(…) is underused

· Java Zone

Navigate the Maze of the End-User Experience and pick up this APM Essential guide, brought to you in partnership with CA Technologies

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)) {
  doSomething(value);
}

// 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)) {
  doSomething();
}

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

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

http://stackoverflow.com/questions/7390571/java-in-operator

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

https://docs.google.com/Doc?id=ddv8ts74_4cbnn5mhj&pli=1

Too bad it never made it into the JLS…

 

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

Thrive in the application economy with an APM model that is strategic. Be E.P.I.C. with CA APM.  Brought to you in partnership with CA Technologies.

Topics:

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
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.
Subscribe

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

{{ parent.tldr }}

{{ parent.urlSource.name }}