Java ... operator

Filthy Rich Clients presents this code:

public ImageLoadingWorker(JTextArea log, JPanel viewer, String... filenames) {} 

What exactly ... means?

+6
java variadic-functions
source share
5 answers

It is used for variable arguments .

+17
source share

This means that all parameters passed to ImageLoadingWorker , starting from the third, can be accessed using the String array named filenames .

+4
source share

This means that you can pass any number of values ​​for filenames , for example. "foo", "bar", "car", "bus", etc. This is called varargs . To clarify further, both of the following lists are valid:

 ImageLoadingWorker(log, viewer, "foo", "bar") ImageLoadingWorker(log, viewer, "foo", "bar", "car", "bus") 
+4
source share

it is varargs, new in java 5. This means that you can have as many file names as you want in a method call.

+3
source share

From the point of view of the method (or constructor, in your case), this is just another way to write '[]' and is valid only for the last parameter of the method. This means that the method receives an array of strings in the filenames parameter.

For callers of this method (which means people who write code that calls the method), this is better: they can choose whether to give a String[] object or any number of String objects (from 0 to the method size limit allows), and then the compiler creates for you an array with these objects.

So, when called, now you can write

  ... = new ImageLoadingWorker(area, viewer, file1, file2, file3); 

and the compiler creates

  ... = new ImageLoadingWorker(area, viewer, new String[]{file1, file2, file3}); 

for you.

(If there is another method that takes the exact number of lines and other arguments, this is preferable to varargs-one.)

When such a method (or constructor) is called with a parameterized type containing a type variable (for the varargs parameter), the compiler generates a warning, since it cannot really create such an array and will use the erase type array instead.

+3
source share

All Articles