How to add new element to Varargs?

老子叫甜甜 提交于 2020-01-11 08:32:49

问题


I have a method

public boolean findANDsetText  (String Description, String ... extra ) {

inside I want to call another method and pass it extras but I want to add new element (Description) to extras.

     object_for_text = getObject(find_arguments,extra);

How can I do that in java? What would the code look like?

I tired to accommodate code from this question but couldn't make it work.


回答1:


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



回答2:


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;



回答3:


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

    // ...
}



回答4:


Use Arrays.copyOf(...) :

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

object_for_text = getObject(find_arguments,extra2);



回答5:


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;

  }



回答6:


With Java 11 use as parameter for a new List:

List<String> templateArguments = new ArrayList<(Arrays.asList(args));
templateArguments.add(throwable.getMessage());
String.format(template, templateArguments.toArray());


来源:https://stackoverflow.com/questions/11321784/how-to-add-new-element-to-varargs

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