如何向Varargs添加新元素?
我有一个方法
public boolean findANDsetText (String Description, String ... extra ) {
在里面我想调用另一个方法并传递extras
但我想添加新的元素(描述)到额外的。
object_for_text = getObject(find_arguments,extra);
我怎么能在java中这样做? 代码会是什么样的?
我厌倦了容纳这个问题的代码,但无法使其工作。
extra
只是一个String
数组。 因此:
List extrasList = Arrays.asList(extra); extrasList.add(description); getObject(find_arguments, extrasList.toArray());
您可能需要使用extrasList.toArray()
的generics类型。
你可以更快但更冗长:
String[] extraWithDescription = new String[extra.length + 1]; int i = 0; for(; i < extra.length; ++i) { extraWithDescription[i] = extra[i]; } extraWithDescription[i] = description; getObject(find_arguments, extraWithDescription);
为了扩展这里的一些其他答案,可以更快地完成数组复制
String[] newArr = new String[extra.length + 1]; System.arraycopy(extra, 0, newArr, 0, extra.length); newArr[extra.length] = Description;
你的意思是这样的吗?
public boolean findANDsetText(String description, String ... extra) { String[] newArr = new String[extra.length + 1]; int counter = 0; for(String s : extra) newArr[counter++] = s; newArr[counter] = description; // ... Foo object_for_text = getObject(find_arguments, newArr); // ... }
就这么简单……
将Var-args视为如下……
例:
在上面的例子中,第二个参数是“String … extra”
所以你可以像这样使用:
extra[0] = "Vivek"; extra[1] = "Hello";
要么
for (int i=0 ; i
使用Arrays.copyOf(...)
:
String[] extra2 = Arrays.copyOf(extra, extra.length+1); extra2[extra.length] = description; object_for_text = getObject(find_arguments,extra2);