How to add new element to Varargs?

ε祈祈猫儿з 提交于 2019-12-01 17:21:26

extra is just a String array. As such:

List<String> extrasList = Arrays.asList(extra);
extrasList.add(description);
getObject(find_arguments, extrasList.toArray());

You may need to mess with the generic type of extrasList.toArray().

You can be faster but more verbose:

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

To expand on some of the other answers here, the array copy could be done a bit faster with

String[] newArr = new String[extra.length + 1];
System.arraycopy(extra, 0, newArr, 0, extra.length);
newArr[extra.length] = Description;
Eng.Fouad

Do you mean something like this?

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

    // ...
}

Use Arrays.copyOf(...) :

String[] extra2 = Arrays.copyOf(extra, extra.length+1);
extra2[extra.length] = description;

object_for_text = getObject(find_arguments,extra2);

Its simply this way...

Treat the Var-args as below...

Example:

In your above example the 2nd parameter is "String... extra"

So you can use like this:

extra[0] = "Vivek";
extra[1] = "Hello";

Or

for (int i=0 ; i<extra.length ; i++)

  {

          extra[i] = value;

  }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!