Re: what is the initial value of arrays of object
Patricia Shanahan <pats@acm.org> wrote:
I like initializer blocks as a very general solution to this class of
problem.
If you've devised some idiom for this kind of job, you effectively
agree to zerg, that there is indeed some use for that job. :-)
X[] myXArray = new X[y];
{
for(int i=0; i<myXArray.length; i++){
myXArray[i] = new X();
}
}
X[] myXArray = new X[y]();
int[] myInts = new int[10];
{
Arrays.fill(myInts, 1);
}
int[] myInts = new int[10](1);
This solution avoids extra syntax, and yet keeps the full initialization
together, rather than spreading it between the declarations and the
constructor. It is far more powerful than any special case syntax could
be.
Zerg's proposal avoids verbose wording and yet keeps the full
initialisation together with the declaration and the constructor
(provided that indeed the thusly construed items are what is
wanted). It is far more concise than calling Array.fill for
primitives or looping for Objects.
PS: where I disagree to zerg is, that I'd actually *want* the
multiple-evaluation and making use of possible sideeffects:
List<String> list=getStringList(); // just for context
Iterator<String> it=list.iterator(); // just for context
MyObj moArr=new MyObj[list.size()](it.next());
and have an array of MyObj's allocated and construed with
each element of an equally-sized Collection as the respective
array-element's constructor's argument.
or:
int i=0,ia[]=new int[N](i++);
But I do expect that others may find this abhorrently bad, so
I probably won't spend much of my energy in proposing it further.