6

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

Community
  • 1
  • 1
nativist.bill.cutting
  • 1,292
  • 3
  • 11
  • 19
  • 4
    This won't compile in Java. – Erik Kaplun Oct 05 '13 at 13:11
  • I suspect it was merely a typo on the part of the prof. Don't turn it into a federal case (or worse yet, a Congressional catfight). – Hot Licks Oct 05 '13 at 13:15
  • (And it should be noted that the term "initialize" must be carefully interpreted. The `new` operation allocates and initializes an array of *references* to Foo, but it does not create any Foo objects -- the array is initially all `null` references.) – Hot Licks Oct 05 '13 at 13:17
  • I glanced briefly at the notes. Aside from the typos they appear to be reasonable and a logical progression. – Hot Licks Oct 05 '13 at 13:20

5 Answers5

7

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();
}
Erik Kaplun
  • 37,128
  • 15
  • 99
  • 111
  • 1
    @JeroenVannevel: amended my answer. – Erik Kaplun Oct 05 '13 at 13:13
  • @nativist.bill.cutting: Why couldn't you create your own example and verify that it doesn't compile? You say you're not lazy, but how did you try this before asking Eric to do it for you? – Jon Skeet Oct 05 '13 at 13:19
  • @nativist.bill.cutting: so what made you unaccept my answer and accept another one that says the same thing except with no explanation? – Erik Kaplun Oct 07 '13 at 13:09
1
Foo[] foos = new Foo[12] ; //declaring array 

for(int i=0;i<12;i++){
   foos[i] = new Foo();  //initializing the array with foo object

}
Prabhakaran Ramaswamy
  • 25,706
  • 10
  • 57
  • 64
1

You can't do this

Foo foos = new Foo[12] ;

change to

Foo[] foos = new Foo[12];

there was a typo in the document on page 9. Also there's a typo on page 10

int[] grades = new int[3]

I would not read the whole document if the typos are on each page.

Roman C
  • 49,761
  • 33
  • 66
  • 176
0

Declare by this way.

Foo[] foos = new Foo[12];
Erik Kaplun
  • 37,128
  • 15
  • 99
  • 111
KhAn SaAb
  • 5,248
  • 5
  • 31
  • 52
0
//declaring array of 12 Foo elements in Java8 style
Foo[] foos = Stream.generate(Foo::new).limit(12).toArray(Foo[]::new);

// instead of
Foo[] foos = new Foo[12];
for(int i=0;i<12;i++){
   foos[i] = new Foo();

}
alex.b
  • 1,448
  • 19
  • 23