I just looked at this SO Post:
However, the Columbia professor's notes does it the way below. See page 9.
Foo foos = new Foo[12] ;
Which way is correct? They seem to say different things.
Particularly, in the notes version there isn't []
.
Before creating an array of objects, we must create an instance of the class by using the new keyword. We can use any of the following statements to create an array of objects. Syntax: ClassName obj[]=new ClassName[array_length]; //declare and instantiate an array of objects.
Initialize Arrays in C# with Known Number of Elements We can initialize an array with its type and size: var students = new string[2]; var students = new string[2]; Here, we initialize and specify the size of the string array.
This simply won't compile in Java (because you're assigning a value of an array type to a variable of a the non-array type Foo
):
Foo foos = new Foo[12];
it's rejected by javac
with the following error (See also: http://ideone.com/0jh9YE):
test.java:5: error: incompatible types
Foo foos = new Foo[12];
To have it compile, declare foo
to be of type Foo[]
and then just loop over it:
Foo[] foo = new Foo[12]; # <<<<<<<<<
for (int i = 0; i < 12; i += 1) {
foos[i] = new Foo();
}
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