2

When I write the constructor in Java like this:

import java.io.IOException;
import java.io.OutputStream;

public class MultiOutputStream extends OutputStream{

    OutputStream[] oStream;

    public MultiOutputStream(OutputStream oStream) { 
        this.oStream = oStream;
        // TODO Auto-generated constructor stub
    }

    @Override
    public void write(int arg0) throws IOException {
        // TODO Auto-generated method stub

    }
}

Eclipse now says: Type mismatch: cannot convert from OutputStream to OutputStream[]. So Eclipse corrected my constructor like this:

import java.io.IOException;
import java.io.OutputStream;

public class MultiOutputStream extends OutputStream{

    OutputStream[] oStream;

    public MultiOutputStream(OutputStream... oStream) {
        this.oStream = oStream;
        // TODO Auto-generated constructor stub
    }

    @Override
    public void write(int arg0) throws IOException {
        // TODO Auto-generated method stub

    }

}

What does these points stand for?

Thanks in advance!

aGer
  • 466
  • 1
  • 4
  • 17

3 Answers3

6

They are called "varargs", see http://docs.oracle.com/javase/7/docs/technotes/guides/language/varargs.html.

The three periods after the final parameter's type indicate that the final argument may be passed as an array or as a sequence of arguments.

JP Moresmau
  • 7,388
  • 17
  • 31
3

It's a syntaxic sugar called varargs.

public void method(int... varargs) { }

You can call this method using multiple argument, for example: method(3, 14), but also method(42).
It's a common way to deal with method with an indeterminate numbers of arguments, it's used for example in String::format.

The compiler will automatically gather the arguments into an array behind the hood. In this code, varargs is an array of int, and so you could easily loop over it.

public void method(int... varargs) { 
  for(int i=0; i < varargs.length; i++) {
    System.out.println("Argument n°"+i+" is "+varargs[i]);
  }
}
NiziL
  • 5,068
  • 23
  • 33
1

These points are called varargs. You can read more about them here.

To summarize, they are used in order to allow infinite amount of parameters of that type to a method. This allows for easier access and cleaner code. The vararg is like an array when you try to use it.

Constant
  • 780
  • 1
  • 5
  • 19