Passing optional arguments in Java

5

I'm trying to learn how the class works SwingWorker<T,V> , I have already done another question regarding one of his methods.

Looking at the source code of this class, I found the publish() method written as follows:

SafeVarargs
    @SuppressWarnings("varargs") // Passing chunks to add is safe
    protected final void publish(V... chunks) {
        synchronized (this) {
            if (doProcess == null) {
                doProcess = new AccumulativeRunnable<V>() {
                    @Override
                    public void run(List<V> args) {
                        process(args);
                    }
                    @Override
                    protected void submit() {
                        doSubmit.add(this);
                    }
                };
            }
        }
        doProcess.add(chunks);
    }

In the "signature" method, it receives V... chunks as argument. However, after testing this class a bit, I noticed that even if I set this type V at the time of starting a variable, example SwingWorker<Void, Integer> worker; ( V is represented by Integer ), and pass publish() no parameter, no syntax error is generated, and the code works normally.

In the light of the above, I ask: what is the name of this way of passing arguments without being obligatory and how does the JVM treat this type of method?     

asked by anonymous 22.03.2016 / 23:17

1 answer

7

It is essentially answered in the renan question . And it's good to say that the parameter is not optional, the arguments can be ( see the difference between them ).

Because the arguments are encapsulated in an array that is the parameter, the parameter variable will always exist, so there will never be an error. If you do not pass any arguments, the array , in this case, chuncks will have zero elements, but will still be an array .

Consider if varargs did not exist. The syntax would look like this:

void publish(V[] chunks)

and calls could look like this:

obj.publish(new V[] {1, 2, 3});
obj.publish(new V[] {});

With this syntactic sugar, it can look like this:

obj.publish(1, 2, 3);
obj.publish();
    
22.03.2016 / 23:45