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:28

They are completely equivalent. int [] array is the preferred style. int array[] is just provided as an equivalent, C-compatible style.

查看更多
荒废的爱情
3楼-- · 2018-12-31 02:29

There is one slight difference, if you happen to declare more than one variable in the same declaration:

int[] a, b;  // Both a and b are arrays of type int
int c[], d;  // WARNING: c is an array, but d is just a regular int

Note that this is bad coding style, although the compiler will almost certainly catch your error the moment you try to use d.

查看更多
怪性笑人.
4楼-- · 2018-12-31 02:29

It is an alternative form, which was borrowed from C, upon which java is based.

As a curiosity, there are three ways to define a valid main method in java:

  • public static void main(String[] args)
  • public static void main(String args[])
  • public static void main(String... args)
查看更多
何处买醉
5楼-- · 2018-12-31 02:30

Yep, exactly the same. Personally, I prefer

int[] integers; 

because it makes it immediately obvious to anyone reading your code that integers is an array of int's, as opposed to

int integers[];

which doesn't make it all that obvious, particularly if you have multiple declarations in one line. But again, they are equivalent, so it comes down to personal preference.

Check out this page on arrays in Java for more in depth examples.

查看更多
临风纵饮
6楼-- · 2018-12-31 02:31

There isn't any difference between the two; both declare an array of ints. However, the former is preferred since it keeps the type information all in one place. The latter is only really supported for the benefit of C/C++ programmers moving to Java.

查看更多
余生无你
7楼-- · 2018-12-31 02:31

Both have the same meaning. However, the existence of these variants also allows this:

int[] a, b[];

which is the same as:

int[] a;
int[][] b;

However, this is horrible coding style and should never be done.

查看更多
登录 后发表回答