How to initialize an array of objects?

纵然是瞬间 提交于 2019-11-27 06:13:55

问题


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


回答1:


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



回答2:


Foo[] foos = new Foo[12] ; //declaring array 

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

}



回答3:


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.




回答4:


Declare by this way.

Foo[] foos = new Foo[12];



回答5:


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

}


来源:https://stackoverflow.com/questions/19198196/how-to-initialize-an-array-of-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!