Java ... operator
In Filth开发者_开发问答y Rich Clients this code is presented:
public ImageLoadingWorker(JTextArea log, JPanel viewer, String... filenames) {}
What exactly does ... mean?
It's used for variable arguments.
It means all parameters passed to ImageLoadingWorker
starting with the third one can be accessed using a String
array called filenames
.
It means you can pass any number of values for filenames
, e.g. "foo", "bar", "car", "bus", etc. It is called varargs
. To explain further both calls below are valid:
ImageLoadingWorker(log, viewer, "foo", "bar")
ImageLoadingWorker(log, viewer, "foo", "bar", "car", "bus")
it is varargs, new in java 5. It means you can have as many filenames as you want in your method call.
From the viewpoint of the method (or constructor, in your case) itself, it is simply another way to write '[]', and only valid for the last parameter of a method. This is, the method gets an array of Strings in the filenames parameter.
For the callers of this method (meaning the humans that write the code calling the method) it is better: They can choose whether to give a String[]
object or any number of String
objects (from 0 to how much the method size limit allows), and the compiler then creates an array for you with these objects.
So, when calling you can now 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 taking the precise number of Strings and same other arguments, it is preferred instead of the varargs-one.)
When calling such a method (or constructor) with a parametrized type containing a type variable (for the varargs parameter), the compiler emits a warning since he can't really create such an array, and will instead use an array of the erasure type.
精彩评论