avatar
an Array question# Java - 爪哇娇娃
P*y
1
Why can't I do the following:
int [] myArray;
myArray = {1, 2};
Thanks
avatar
o*v
2
int[] myArray = new int[2];
myArray[0]=1
myArray[1]=2

【在 P****y 的大作中提到】
: Why can't I do the following:
: int [] myArray;
: myArray = {1, 2};
: Thanks

avatar
P*y
3
thank you, ooev. I just do not understand why it is illegal to
do it on my way.

【在 o**v 的大作中提到】
: int[] myArray = new int[2];
: myArray[0]=1
: myArray[1]=2

avatar
o*v
4
or
int[] myArray = {1, 2};

【在 P****y 的大作中提到】
: Why can't I do the following:
: int [] myArray;
: myArray = {1, 2};
: Thanks

avatar
c*y
5
You need to specify how much memory to allocate to the array when defining it.

【在 P****y 的大作中提到】
: thank you, ooev. I just do not understand why it is illegal to
: do it on my way.

avatar
m*t
6
I'm too lazy to test it now, but I think you want to do:
int[] myArray = new int[]{1, 2};

【在 o**v 的大作中提到】
: or
: int[] myArray = {1, 2};

avatar
o*v
7
i tested b4 i posted. 【 在 magicfat (魔法胖子) 的大作中提到: 】
avatar
m*t
8
you are right, looks like if you want to assign it in the declaration
you can do either
int[] myArray = new int[]{1, 2};
or simply
int[] myArray = {1, 2};
But if it's in an assignment, you can't omit "new int[]".

【在 o**v 的大作中提到】
: i tested b4 i posted. 【 在 magicfat (魔法胖子) 的大作中提到: 】
avatar
c*g
9
Java array is an object, to create an object, you need to
1) declare
2) initialize (use new to assign a size).
So you can say:
int[] myArray;
myArray = new int[4];
But one of many special things about an array is, you can also
initialize its members, either in an explicitive (such as a loop),
or an implicitvie way. like:
int[] myArray;
myArray = new int[] {1, 2};
you can do this in one line: int[] myArray = new int[] {1, 2};
ALSO, there is a shortcut for the above one line initi

【在 P****y 的大作中提到】
: Why can't I do the following:
: int [] myArray;
: myArray = {1, 2};
: Thanks

相关阅读
logo
联系我们隐私协议©2024 redian.news
Redian新闻
Redian.news刊载任何文章,不代表同意其说法或描述,仅为提供更多信息,也不构成任何建议。文章信息的合法性及真实性由其作者负责,与Redian.news及其运营公司无关。欢迎投稿,如发现稿件侵权,或作者不愿在本网发表文章,请版权拥有者通知本网处理。