简体   繁体   English

扩展数组以传递给varargs

[英]Expanding an array to pass into varargs

Given this function signature: 鉴于此功能签名:

public static void test(final String... args) {}

I would like to fit a string and an array of strings into the args : 我想在args输入一个字符串和一个字符串数组:

test("a", new String[]{"b", "c"});

But it is not possible because the second argument is not expanded. 但这是不可能的,因为第二个论点没有扩展。

So is it possible to expand an array to fit into varargs? 那么是否可以扩展数组以适应varargs?

If that is not possible, what is the shortest way to construct a concatenated string array given one string and a string array? 如果这是不可能的,给定一个字符串和一个字符串数组构建连接字符串数组的最短方法是什么? Eg: 例如:

String a = "a";
String[] b = new String[]{"b", "c"};
String[] c = // To get: "a", "b", "c"

Thank you. 谢谢。

I don't know any other shorter ways but this is pretty clean to me. 我不知道其他任何更短的方式,但这对我来说非常干净。 With plain java ( without ant libraries ) 用普通的java( 没有ant库

String a = "a";
String[] b = new String[] { "b", "c" };
String[] c = new String[b.length + 1];
c[0]=a;
System.arraycopy(b, 0, c, 1, b.length);

That will work no matter what is the size of b 无论b的大小是多少都可以

You can use Guava's ObjectArrays.concat(T, T[]) method: 您可以使用Guava的ObjectArrays.concat(T, T[])方法:

String a = "a";
String[] b = new String[]{"b", "c"};
String[] c = ObjectArrays.concat(a, b);

Notice the order of arguments. 注意参数的顺序。 Invoking with (b, a) will also work, but that will append the element to the array rather than prepend (which is what you seem to want). 使用(b, a)调用也可以,但是这会将元素附加到数组而不是prepend(这是你想要的)。 This internally uses System.arraycopy() method. 这在内部使用System.arraycopy()方法。

您可以创建一个单独的数组,并首先将String “a”放入该数组,然后使用System.arraycopy()将数组b []复制到数组中,然后将新数组传递给该方法。

You can use StringBuilder : 您可以使用StringBuilder

StringBuilder sb = new StringBuilder();
sb.append(a);
for(String s : b) {
    sb.append(s);
}

And then you can convert it back to ArrayList or array of Strings... 然后你可以将它转换回ArrayList或字符串数​​组......

Shortest way which comes to my mind (BUT not clean code ): 我想到的最短路(但不是干净的代码 ):

test((a + "," + Arrays.toString(b)).replaceAll("[\\[\\] ]", "").split(","));

Test: 测试:

public static void main(String[] args) {
    String a = "a";
    String[] b = new String[] {"b", "c"};

    System.out.println(Arrays.toString(
            (a + "," + Arrays.toString(b)).replaceAll("[\\[\\] ]", "").split(",")));

}

Output: 输出:

[a, b, c]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM