P****y 发帖数: 707 | 1 Why can't I do the following:
int [] myArray;
myArray = {1, 2};
Thanks |
o**v 发帖数: 1662 | 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
|
P****y 发帖数: 707 | 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
|
o**v 发帖数: 1662 | 4 or
int[] myArray = {1, 2};
【在 P****y 的大作中提到】 : Why can't I do the following: : int [] myArray; : myArray = {1, 2}; : Thanks
|
c*y 发帖数: 137 | 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.
|
m******t 发帖数: 2416 | 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};
|
o**v 发帖数: 1662 | 7 i tested b4 i posted. 【 在 magicfat (魔法胖子) 的大作中提到: 】 |
m******t 发帖数: 2416 | 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 (魔法胖子) 的大作中提到: 】
|
c**g 发帖数: 274 | 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
|