1

Sorry but I'm not able to phrase this question properly without an example. Say oneMethod has such a signature:

void oneMethod(String... strings);

I call oneMethod by

void callOneMethod(int numStrings) {
    oneMethod("s" + 0, "s" + 1, ..., "s" + (numStrings - 1));
}

How should I write my callOneMethod?

Also, I very much appreciate it if anyone can help rephrase this question better :)

2

1 Answer 1

2

The strings parameter is very similar to an array parameter. Therefore you can create an array to pass to oneMethod:

void callOneMethod(int numStrings) {
    String[] a = new String[numStrings];
    for (int i = 0; i < numStrings; i++) {
        a[i] = "s" + i;
    }
    oneMethod(a);
}

Clarification

Of course still your oneMethod(String... strings) method is used.

Sign up to request clarification or add additional context in comments.

4 Comments

Thank you for the answer. However, I'm passing all numStrings number of strings into oneMethod at the same time. So what arguments oneMethod accepts is decided at runtime...
@goldfrapp04 this answer is the correct one. This allows you to pass whatever number of arguments you want. What is the issue?
Oh! ok I guess I didn't understand varargs clearly. So essentially it sees the arguments as an array?
@goldfrapp04: Form inside a method with a vararg parameter you treat it as a array. When calling the method you can pass either an array (like in my code snipplet) or arbitrary number of arguments have the right type (e.g. oneMethod("a", "b", "c")).

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.