开发者

Passing mix of T and T[] to a Java varargs method

Suppose you have a Java method

void foobar(int id, String ... args)

and want to pass both String arrays and Strings into the method. Like this

String arr1[]={"adas", "adasda"};
String arr2[]={"adas", "adasda"};
foobar(0, "adsa", "asdas");
foobar(1, arr1);
foobar(2, arr1, arr2);
foobar(3, arr1, "asdas", arr2);

In Python there is "*" for this. Is there some way better than such rather ugly helper method:

static String[] concat(Object... args) {
    List<String> result = new ArrayList<String>();
    for (Object arg : args) {
        if (arg instanceof String) {
            String s = (String) arg;
            result.add(s);
        } else if (arg.getClass().isArray() && arg.getClass().getComponentType().equals(String.class)) {
            String arr[] = (String[]) arg;
            for (String s : arr) {
                result.add(s);
            }
        } else {
            throw new RuntimeException();
        }
    }
    return result.toArray(new String[result.size()]);
}

which allows开发者_Go百科

foobar(4, concat(arr1, "asdas", arr2));


Java doesn't have any built in syntactic sugar for this, but your helper method could be a lot nicer:

private static String[] concat(Object... stringOrArrays) {
    List<String> result = new ArrayList<String>();
    for (Object stringOrArray : stringOrArrays) {
        if (stringOrArray instanceof String) {
            result.add((String) stringOrArray);
        } else if (stringOrArray instanceof String[]) {
            Collections.addAll(result, (String[]) stringOrArray);
        } else if (stringOrArray == null) {
            results.add(null)
        } else {
            throw new RuntimeException(stringOrArray + " not a String or String[]");
        }
    }
    return result.toArray(new String[0]);
}

I could come up with a one liner (to avoid the method) but I don't recommend it:

    foobar(1, new ArrayList<String>() {{
        addAll(Arrays.asList(arr1));
        addAll(Arrays.asList(arr2));
        add(arr3);
    }}.toArray(new String[0]));

The only advantage the one-liner has is type safety.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜