Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 567
Radek Avatar asked Jul 04 '12 02:07

Radek


People also ask

Can Varargs take an array?

Every time we use varargs, the Java compiler creates an array to hold the given parameters. In this case, the compiler creates an array with generic type components to hold the arguments. The varargs usage is safe if and only if: We don't store anything in the implicitly created array.

How do you handle varargs in Java?

Important Points regarding Varargs Before JDK 5, variable length arguments could be handled in two ways: One was using overloading, other was using array argument. There can be only one variable argument in a method. Variable argument (Varargs) must be the last argument.


1 Answers

Use Arrays.copyOf(...) :

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

object_for_text = getObject(find_arguments,extra2);
like image 155
lenborje Avatar answered Sep 30 '22 10:09

lenborje