Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Java’s Arrays.asList(…) is underused

DZone's Guide to

Java’s Arrays.asList(…) is underused

· Java Zone ·
Free Resource

Verify, standardize, and correct the Big 4 + more– name, email, phone and global addresses – try our Data Quality APIs now at Melissa Developer Portal!

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/

Developers! Quickly and easily gain access to the tools and information you need! Explore, test and combine our data quality APIs at Melissa Developer Portal – home to tools that save time and boost revenue. 

Topics:

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}