问题
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