2

I want to prepend a String to a variable list of String arguments.

public String myMethod(String... args) {
    return myOtherMethod("some string" + args);
}

Now, this of course will not work, because you cannot add these two types as such. How can I insert this string at the beginning of the list and then call myOtherMethod()?

EDIT: myOtherMethod() takes another String... as its argument. I am also limited to Java 7.

4
  • What is the type of myOtherMethod? Does it accept another String...? Just one String? Commented Jun 18, 2015 at 20:21
  • It is another String... Commented Jun 18, 2015 at 20:23
  • 1
    So you only need to create a new array with "some string" as the first element, right? Commented Jun 18, 2015 at 20:29
  • do you want to return the big concatenated string from myOtherMethod? Commented Jun 18, 2015 at 20:30

1 Answer 1

3

There isn't a way around creating a new String[], like so:

public String myMethod(String... args) {
  String[] concatenatedArray = new String[args.length + 1];
  concatenatedArray[0] = "other string";
  for (int i = 0; i < args.length; i++) { // or System.arraycopy...
    concatenatedArray[i + 1] = args[i];
  }
  return myOtherMethod(concatenatedArray);
}

Or, if third-party libraries are allowed, using Guava you could just write

return myOtherMethod(ObjectArrays.concat("other string", args));
Sign up to request clarification or add additional context in comments.

2 Comments

You can also use System.arraycopy(args, 0, concatenatedArray, 1, concatenatedArray.length - 1); rather than use the for.
Yep. (As I alluded to in the comment.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.