Search code examples
javavariadic-functions

How to add new element to Varargs?


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.


Solution

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