How to initialize an array of objects?

I just looked at this SO Post:

However , a professor of Columbia notes does this below. See page nine.

Foo foos = new Foo[12] ; 

Which way is right? They seem to say different things.

In particular, there are no notes in the version [] .

+6
source share
5 answers

It just won’t compile in Java (because you assign an array type value to a type variable without a Foo array):

 Foo foos = new Foo[12]; 

it is rejected by javac with the following error (see also: http://ideone.com/0jh9YE ):

 test.java:5: error: incompatible types Foo foos = new Foo[12]; 

For it to compile, declare Foo as type Foo[] , and then just flip it:

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

You cannot do it

 Foo foos = new Foo[12] ; 

change to

 Foo[] foos = new Foo[12]; 

there was a typo in the document on the page. There is also a typo on page 10

 int[] grades = new int[3] 

I would not read the entire document if typos are on every page.

+1
source

Declare in this way.

 Foo[] foos = new Foo[12]; 
0
source
 //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(); } 
0
source

Source: https://habr.com/ru/post/955301/


All Articles