如何初始化对象的数组? [英] How to initialize an array of objects?

查看:177
本文介绍了如何初始化对象的数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是看着这个 SO帖子:

不过,哥伦比亚大学教授的笔记做它下面的方式。参见第9页。

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.

特别是,在Notes版本没有 []

Particularly, in the notes version there isn't [].

推荐答案

这根本不​​会用Java编译(因为你分配一个数组类型的值,以一个非数组类型的变量

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];

它是由的javac ,出现以下错误拒绝(参见:的http:// ideone。 COM / 0jh9YE ):

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

这篇关于如何初始化对象的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆