Is there any method, other than through static factory methods or builder patterns, to handle default constructor parameters of type array?
There is plenty of fruitful discussion here regarding how to do this with builder patterns and static factory methods, and there are plenty of other examples out there of how to handle various constructors of varying parameter count, but all these patterns appear to include only parameters of simple type (e.g. int, double, etc.), which I have no problem getting to work. I am trying to have a default parameter of type array, and am unable to achieve this with the standard constructor setup.
It tried a few approaches to this and they all result in errors of some kind, so I am searching for an alternative, still making use of a constructor pattern. The first approach:
public class MyClass{
double[] mWeights;
public MyClass(){
double[] weights = {1, 1, 1}
this(weights);
}
public MyClass(double[] weights){
this.mWeights = weights
}
}
but this results in an error:
Call to 'this()' must be first statement in constructor body
Alternatively, I tried:
public class MyClass{
double[] mWeights = new double[] {1, 1, 1};
public ActionDistribution(){
this(mWeights);
}
public ActionDistribution(double[] weights){
this.mWeights = weights;
}
}
but this results in an error:
Cannot reference 'MyClass.mWeights' before supertype constructor has been called.
Lastly, I tried:
public class MyClass{
double[] Mweights;
public ActionDistribution(){
this({1, 1, 1});
}
public ActionDistribution(double[] weights){
this.mWeights = weights;
}
}
but this results in the error:
Array initializer is not allowed here
Any ideas as to how I can set up a constructor to handle a default array without the use of static factory methods or builder patterns? Bonus points if you have a solution that works for any generic type (and not just arrays), and even more points for explaining why this is possible for simpler data types and not arrays.
Edit: In case it is not clear, in a working form of the code above, I am hoping to later call
MyClass myClass = new MyClass();
and have it result in a myClass object with a field myClass.mWeights
of value {1, 1, 1}