Java 如何初始化一个对象数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19198196/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to initialize an array of objects?
提问by nativist.bill.cutting
I just looked at this SO Post:
我刚刚看了这个SO Post:
However, the Columbia professor's notesdoes it the way below. See page 9.
但是,哥伦比亚大学教授的笔记是按照以下方式进行的。见第 9 页。
Foo foos = new Foo[12] ;
Which way is correct? They seem to say different things.
哪种方式是正确的?他们似乎在说不同的话。
Particularly, in the notes version there isn't []
.
特别是,在笔记版本中没有[]
.
采纳答案by Erik Kaplun
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
):
这根本不会在 Java 中编译(因为您将数组类型的值分配给非数组类型的变量Foo
):
Foo foos = new Foo[12];
it's rejected by javac
with the following error (See also: http://ideone.com/0jh9YE):
它被拒绝javac
并出现以下错误(另请参阅: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[]
,然后循环遍历它:
Foo[] foo = new Foo[12]; # <<<<<<<<<
for (int i = 0; i < 12; i += 1) {
foos[i] = new Foo();
}
回答by Prabhakaran Ramaswamy
Foo[] foos = new Foo[12] ; //declaring array
for(int i=0;i<12;i++){
foos[i] = new Foo(); //initializing the array with foo object
}
回答by KhAn SaAb
Declare by this way.
以此方式声明。
Foo[] foos = new Foo[12];
回答by Roman C
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
第 9 页的文档中有一个错字。第 10 页上也有一个错字
int[] grades = new int[3]
I would not read the whole document if the typos are on each page.
如果每一页都有错别字,我就不会阅读整个文档。
回答by alex.b
//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();
}