Reputation: 1409
public MonomialPolynomial(double... coeffs){
List<IMonom> monoms = new ArrayList<IMonom>();
for (int i = 0; i < coeffs.length; i++) {
// zero coeffs might yaffect the degree
if(coeffs[i] != 0)
monoms.add(new Monom(coeffs[i], i));
}
super.monoms = monoms;
}
Why do people write double...
and not [] double
when they mean to array?
Is there a special meaning for this?
Upvotes: 0
Views: 112
Reputation: 20961
double...
declares it a "var args" parameter -- inside your method it's identical to double[]
but for the caller, it's much easier to call with varying numbers of arguments (hence var args) without the need to explicitly create an array:
Without var args:
MonomialPolynomial(double[] coeffs) { ...}
...
// explicit array creation necessary
new MonomialPolynomial(new double[] {1, 2, 3)};
With var args:
MonomialPolynomial(double... coeffs) { ...}
...
// array gets created implicitly, so less boilerplate code
new MonomialPolynomial(1, 2, 3);
Edit: One thing to watch out for with var args, only the last argument of a method can be a var args argument. This guarantess there's no ambiguity when calling a method, e.g.
foo(int a, int b...)
is unambigious, because the first argument will always be assigned to a
and anything after that will be go into of b
.
foo(int a..., int... b)
on the other hand is ambigious, there's no way to tell if foo(1, 2, 3)
means a={1} and b={2, 3}
or a={1, 2} and b={3}
.
Upvotes: 4
Reputation: 17537
It is the vararg
feature, that is, all the arguments the function gets are collected into an array. In that case, an array of doubles. The feature is for hardcoded arrays and such. If MonomialPolynomial
were to accept a double[]
, you would have to use such oneliners:
MonomialPolynomial(new double[] {1, 2, 3});
But with variable arguments you may write a bit neater code:
MonomialPolynomial(1, 2, 3);
Upvotes: 0
Reputation: 44808
double...
is a varargs (variable arguments) feature. This means you can provide the constructor with an array of double
s, or you can provide the constructor with any number of double
s, and it is put into an array for you. (Example: MonomialPolynomial(1.0, 5.0, 6.0)
.)
Upvotes: 1