0

I have run into the class and respective constructor shown bellow:

public class Something{
    public static final int aConstant = 0;
    public static final int bConstant = 1;

    private final AnotherThing[] otherObjects
    private final float usefulNumber;

    public Something(float usefulNumber, AnotherThing ... otherObjects){
        this.usefulNumber = usefulNumber;
        this.otherObjects = otherObjects;
    }

    //various methods
}

When I put this into Eclipse, no errors are shown. I assume the "..." is some sort of operator, but I am not sure. Can anyone clarify if this is anything, or just something to show that time was saved? (time saving doesn't make any sense because the class only has two attributes)

ChrisMcJava
  • 2,145
  • 5
  • 25
  • 33
  • It's called the *ellipse* operator. – juergen d Aug 11 '13 at 23:57
  • 1
    It's not an operator... it's not called `ellipse`. It's called varargs. It functions like an array, yet can be defined differently. For example, the `String#format()` – Obicere Aug 12 '13 at 00:00
  • http://stackoverflow.com/questions/2367398/what-is-the-ellipsis-for-in-this-method-signature A good answer... – Trae Moore Aug 12 '13 at 00:00

2 Answers2

4

These are called variadic arguments.

As you can see from the code, they arrive as an array.

You can pass varying numbers of arguments for otherObjects.

andy256
  • 2,821
  • 2
  • 13
  • 19
3

This is a notation telling Java that the method or the constructor can take a variable number of parameters. It can be used only after the last parameter type.

The parameters prior to ... are required: callers must specify an expression for each one of them. The rest of the parameters are, however, optional: callers can specify zero, one, two, three, or as many as they wish. These parameters will be passed to the method or to the constructor as a single array.

In your example the call can be made with as many instances of AnotherThing as the caller wishes. This is a syntactic shorthand for passing an array explicitly:

public Something(float usefulNumber, AnotherThing[] otherObjects) ...
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523