Difference between int[] array and int array[]

2018-12-31 01:53发布

I have recently been thinking about the difference between the two ways of defining an array:

  1. int[] array
  2. int array[]

Is there a difference?

标签: java arrays
25条回答
荒废的爱情
2楼-- · 2018-12-31 02:38

There is no difference in functionality between both styles of declaration. Both declare array of int.

But int[] a keeps type information together and is more verbose so I prefer it.

查看更多
深知你不懂我心
3楼-- · 2018-12-31 02:40

Both are equally valid. The int puzzle[] form is however discouraged, the int[] puzzle is preferred according to the coding conventions. See also the official Java arrays tutorial:

Similarly, you can declare arrays of other types:

byte[] anArrayOfBytes;
short[] anArrayOfShorts;
long[] anArrayOfLongs;
float[] anArrayOfFloats;
double[] anArrayOfDoubles;
boolean[] anArrayOfBooleans;
char[] anArrayOfChars;
String[] anArrayOfStrings;

You can also place the square brackets after the array's name:

float anArrayOfFloats[]; // this form is discouraged

However, convention discourages this form; the brackets identify the array type and should appear with the type designation.

Note the last paragraph.

I recommend reading the official Sun/Oracle tutorials rather than some 3rd party ones. You would otherwise risk end up in learning bad practices.

查看更多
弹指情弦暗扣
4楼-- · 2018-12-31 02:40

Both are ok. I suggest to pick one and stick with it. (I do the second one)

查看更多
零度萤火
5楼-- · 2018-12-31 02:42

The Java Language Specification says:

The [] may appear as part of the type at the beginning of the declaration,
or as part of the declarator for a particular variable, or both, as in this
example:

byte[] rowvector, colvector, matrix[];

This declaration is equivalent to:

byte rowvector[], colvector[], matrix[][];

Thus they will result in exactly the same byte code.

查看更多
宁负流年不负卿
6楼-- · 2018-12-31 02:43

In Java, these are simply different syntactic methods of saying the same thing.

查看更多
初与友歌
7楼-- · 2018-12-31 02:44

The two commands are the same thing.

You can use the syntax to declare multiple objects:

int[] arrayOne, arrayTwo; //both arrays

int arrayOne[], intOne; //one array one int 

see: http://java.sun.com/docs/books/jls/second_edition/html/arrays.doc.html

查看更多
登录 后发表回答