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

Try Okta to add social login, MFA, and OpenID Connect support to your Java app in minutes. Create a free developer account today and never build auth again.

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/

Build and launch faster with Okta’s user management API. Register today for the free forever developer edition!

Topics:

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}