Java spread operator

前端 未结 6 917
死守一世寂寞
死守一世寂寞 2021-01-01 10:11

I am not sure of the vocabulary I am using here, please correct me if I\'m wrong.

In Javascript, I had the following code:

let args = [1,2,3];

func         


        
6条回答
  •  长情又很酷
    2021-01-01 10:25

    Contrary to numerous comments, e.g. by @JoeC and @Henry, and incorrect answers, this is possible in Java.

    I'd like to use something like

    doSomething (...args)
    

    instead of calling doSomething(args[0], args[1], args[2]).

    You need:

    public int doSomething (int ... args) {
        int sum = 0;
        for (int i : args)
        {
            sum += i;
        }
        return sum;
    }
    

    I'd like not to change the implementation of such a function.

    Impossible, a priori. Either you are adding exactly three arguments, or as many arguments as were actually passed. Make up your mind about this.

提交回复
热议问题