Java two varargs in one method

后端 未结 12 2228
小鲜肉
小鲜肉 2020-11-27 21:08

Is there any way in java, to create a method, which is expecting two different varargs? I know, with the same object kind it isn\'t possible because the compiler does\'nt kn

12条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-27 21:52

    If you are not going to be passing a large number of Strings most of the time for the first argument you could provide a bunch of overloads that take different numbers of Strings and wrap them in an array before calling a method that takes the array as the first argument.

    public void doSomething(int... i){
        doSomething(new String[0], i);
    }
    public void doSomething(String s, int... i){
        doSomething(new String[]{ s }, i);
    }
    public void doSomething(String s1, String s2, int... i){
        doSomething(new String[]{ s1, s2 }, i);
    }
    public void doSomething(String s1, String s2, String s3, int... i){
        doSomething(new String[]{ s1, s2, s3 }, i);
    }
    public void doSomething(String[] s, int... i) {
        // ...
        // ...
    }
    

提交回复
热议问题