Search code examples
javaarraysverbosity

Is there any varargs array construction method in Java?


There's the very useful Arrays.asList():

public static <T> List<T> asList(T... a) {
    return new ArrayList<T>(a);
}

But there's no Arrays.array():

public static <T> T[] array(T... values) {
    return values;
}

While being absolutely trivial, this would be a quite handy way of constructing arrays:

String[] strings1 = array("1", "1", "2", "3", "5", "8");

// as opposed to the slightly more verbose
String[] strings2 = new String[] { "1", "1", "2", "3", "5", "8" };

// Of course, you can assign array literals like this
String[] strings3 = { "1", "1", "2", "3", "5", "8" };

// But you can't pass array literals to methods:
void x(String[] args);

// doesn't work
x({ "1", "1", "2", "3", "5", "8" });

// this would
x(array("1", "1", "2", "3", "5", "8"));

Is there such a method anywhere else in the Java language, outside of java.util.Arrays?


Solution

  • You could see ArrayUtils from Apache Commons. You must use lib version 3.0 or higher.

    Examples:

    String[] array = ArrayUtils.toArray("1", "2");
    String[] emptyArray = ArrayUtils.<String>toArray();