Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 [].

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
247 views
Welcome To Ask or Share your Answers For Others

1 Answer

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();
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...