adding an unknown number of parameters to a method call in Java

argument-passing, java

Solution

public static void main(String[] args) {
    method(1);      // <- compile error
    method(1,2);
    method(1,2,3);
    method(1,2,3,4);
}

private static void method(int i1, int i2, int...i3) {
    // do something
}

So to answer the question in words: we need 2 arguments at minimum. This passes an empty array ´i3[]´ to the method. Arguments number 3 and above are treated as array values.

It makes no difference...

public static void main(String[] args) {
    method(new int[]{1});      // <- compile error
    method(new int[]{1},2);
    method(new int[]{1},2,new int[]{3,4});
    method(new int[]{1},2,new int[]{3,4},new int[]{5,6});
}

private static void method(int[] i1, int i2, int[]...i3) {
    // do something
}

The varargs parameter has to be the last so it won't conflict with the first array

Problem

I have a method that I want to expand (rather than writing a new method which does basically the same thing), by adding an unknown number of parameters to the end of the list of parameters. If I do this, will I have to change all the calls to the method? I guess the question is, does the unknown parameter include the case there being no parameter passed in at all? For instance, if I have a method: ``` queryFactory(int [] typeArgs, int queryType, int[] ... args){} ``` Could I call: ``` queryFactory(typeArgsInstce, queryTypeInstce) ``` And then when I need to add parameters to the query call: ``` queryFactory(typeArgsInstce, queryTypeInstce, argsInstce) ``` Where `argsInstce` is an array of integers containing extra arguments. I would like to just edit this method rather than writing a new one which does almost the exact same thing except it has some arguments to add to queries. I will simply write another method if by editing this one I will have to change every other call to this method.

Original source

Related problems