Java two varargs in one method

后端 未结 12 2168
小鲜肉
小鲜肉 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 22:07

    A possible API design in which the calling code looks like

        doSomething("a", "b").with(1,2);
    

    through "fluent" API

    public Intermediary doSomething(String... strings)
    {
        return new Intermediary(strings);
    }
    
    class Intermediary
    {
        ...
        public void with(int... ints)
        {
            reallyDoSomething(strings, ints);
        }
    }
    
    void reallyDoSomething(String[] strings, int[] ints)
    {
        ...
    }
    

    The danger is if the programmer forgot to call with(...)

        doSomething("a", "b");  // nothing is done
    

    Maybe this is a little better

        with("a", "b").and(1, 2).doSomething();
    

提交回复
热议问题