Question

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?

Was it helpful?

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();

OTHER TIPS

ArrayUtils from Apache Commons Lang (v3.0 or higher):

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

... or just take the code from Apache and implement "yourself":

public static <T> T[] toArray(final T... items) {
    return items;
}

If you want something shorter than

x(new String[] {"1", "1", "2", "3", "5", "8"});

I use the following which is shorter than the list by itself.

   x("1,1,2,3,5,8".split(","));
// {"1", "1", "2", "3", "5", "8"}

It doesn't use any additional library.


Say you want keys and values you can still use varargs

public static <K,V> Map<K, V> asMap(K k, V v, Object ... keysAndValues) {
    Map<K,V> map = new LinkedHashMap<K, V>();
    map.put(k, v);
    for(int i=0;i<keysAndValues.length;i+=2)
        map.put((K) keysAndValues[i], (V) keysAndValues[i+1]);
    return map;
}

There is really no need for array() method in Java in my opinion. If you want less verbose as you said you can use literals. Or in method parameters you can use varargs (no need for array at all). Based on your title this is what you want to do. You can just do this:

public static void doThings(String... values) {
    System.out.println(values[0]);
}

doThings("This", "needs", "no", "array");

Only if method signature actually has an array you will have to specify the new String[], which is not too much extra writing in my opinion.

Edit: It seems that you do want less verbose way to call methods with arrays as parameters. I wouldn't add external library just of method of one line. This would work for example:

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

yourMethod(toArr("1", "2", "3"));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top