Passing optional arguments in Java

Asked

Viewed 666 times

6

I’m trying to learn how to run the class SwingWorker<T,V>, I’ve even done another question regarding one of its methods.

Looking at the source code of this class, I found the method publish() 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" of the method, it receives V... chunks as argument. However, after testing this class a little, I noticed that even if I define this type V when starting a variable, example SwingWorker<Void, Integer> worker;(The V is represented by Integer), and pass the publish() no parameter, no syntax error is generated, and the code works normally.

Given the above, I question: how is this way of passing arguments without being mandatory and how the JVM treats this type of method?

1 answer

7


Essentially it is answered in question by Renan Gomes. And it is good to say that the parameter is not optional, the arguments are that can be (see the difference between them).

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

Think if the varargs did not exist, the syntax would be like this:

void publish(V[] chunks)

and the calls could be like this:

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

With this syntactic sugar, it can be like this:

obj.publish(1, 2, 3);
obj.publish();

It’s not simpler?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.