Java’s Arrays.asList(…) is underused

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: https://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…

5 thoughts on “Java’s Arrays.asList(…) is underused

  1. Oh shit I used a lot Arrays.asList() but I didn’t know it accepted vargs, so I always did Arrays.asList(new Object[]{obj1,obj2});
    good to know.

  2. Yes, it’s definitely underused. Add a static import for asList and it reads even better.

    On literals, I think they are overrated. I like Scala’s approach much better:

    Array(1, 2, 3, 4)
    List(1, 2, 3, 4)
    Map(1 -> “one”, 2 -> “two”)

    No literals with special syntax there, these are all defined using just methods in Scala’s standard library. Therefore, it’s possible for your own classes to also provide such nice constructors.

    Explanation: Array() is defined on the Array object in the method “apply” (which is the “call operator”) and takes a generic vararg argument. The “->” of map is basically just a method defined for every type and returns a tuple of its receiver and the argument.

    1. Scala has very nice features. “->” being a method (or operator) makes for a very powerful language. I’d like to see operator overloading and re-definition in Java… If that were possible, I’d construct a killer jOOQ supporting true SQL syntax in Java :-)

Leave a Reply