1

Is it possible to pass a dynamic number of arguments to Formatter.format( ) function? I want to pass as all Strings in a String array to format() function.
Something like this,

Formatter format;
format.format("FormatString" , "someString" ,  arrayOfString[0] , arrayOfString[1] , ... , arrayOfString[n] , "anotherString" );
4
  • "I want to pass as all Strings in a String array" did you try it? How did it go? Commented Jan 18, 2016 at 6:17
  • if array is the last argument it's possible. But not possible something like mentioned in the code. Commented Jan 18, 2016 at 6:27
  • From what I remember it is more like "if array is only argument (beside format)" then it is possible. If all elements are of type String then you can wrap them in array and pass it, if some of them can be other type use Object array. Commented Jan 18, 2016 at 6:29
  • thanks..I will try this solution Commented Jan 18, 2016 at 6:40

2 Answers 2

1

Dynamic arguments are basically a form of syntactic sugar for passing an array of arguments to the function. Internally, the dynamic arguments are an array.

public Formatter format(String format, Object ... args)

Is basically the same as

public Formatter format(String format, Object[] args)

Except that in the former case, you don't have to build the array by hand, the compiler will do it for you. But it is still possible to pass an array of arguments, as if the method was written with the latter syntax.

So you can build your own array of dynamic arguments that contains all the arguments that you want to pass:

String[] arrayOfString;

Object[] arguments = new Object[arrayOfString.length + 2];
int argIndex = 0;
arguments[argIndex++] = "someString";
for (int i = 0; i < arrayOfString.length; i++) {
    arguments[argIndex++] = arrayOfString[i];
}
arguments[argIndex++] = "anotherString";

Formatter formatter = new Formatter();
formatter.format("FormatString", arguments);
Sign up to request clarification or add additional context in comments.

Comments

0

You can get away with this simply by using an Array stream:

Formatter formatter = new Formatter();
formatter.format(formatString, Arrays.stream(new Object[][]{array1, array2})
    .flatMap(Arrays::stream).toArray());

Comments

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.