Can anybody explain, why do I have to use this code pattern?
// Create the array to store the CDs.
CD[] cdLibrary = new CD[20];
// Populate the CD library with CD objects.
for (int i=0; i<20; i++)
{ cdLibrary[i] = new CD(); }
I cannot understand why the initialization of objects in an array does not occur when I call new CD[20]. It seems like I'm writing excess code. Can one of these steps be skipped?
I cannot understand why the initialization of objects in an array does not execute in the operator new.
Do you mean this line?
CD[] cdLibrary = new CD[20];
That doesn't initialize 20 objects. It initializes the array, and only the array - the array has 20 elements, each of which has a value of null (a null reference) to start with1. It's like creating a book with a given number of empty pages; if you want the pages to contain information, you have to write on each one separately, which is what the later loop does.
1 I'm assuming that CD is a class type here, for simplicity.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With