Difference between int[] array and int array[]

前端 未结 25 3008
轻奢々
轻奢々 2020-11-21 07:18

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

  1. int[] array
  2. int array[]
  3. <
相关标签:
25条回答
  • 2020-11-21 08:10

    There is no difference.

    I prefer the type[] name format at is is clear that the variable is an array (less looking around to find out what it is).

    EDIT:

    Oh wait there is a difference (I forgot because I never declare more than one variable at a time):

    int[] foo, bar; // both are arrays
    int foo[], bar; // foo is an array, bar is an int.
    
    0 讨论(0)
  • 2020-11-21 08:11

    As already stated, there's no much difference (if you declare only one variable per line).

    Note that SonarQube treats your second case as a minor code smell:

    Array designators "[]" should be on the type, not the variable (squid:S1197)

    Array designators should always be located on the type for better code readability. Otherwise, developers must look both at the type and the variable name to know whether or not a variable is an array.

    Noncompliant Code Example

    int matrix[][];   // Noncompliant
    int[] matrix[];   // Noncompliant
    

    Compliant Solution

    int[][] matrix;   // Compliant
    
    0 讨论(0)
  • 2020-11-21 08:13

    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.

    0 讨论(0)
  • 2020-11-21 08:14

    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.

    0 讨论(0)
  • 2020-11-21 08:15

    when declaring a single array reference, there is not much difference between them. so the following two declarations are same.

    int a[];  // comfortable to programmers who migrated from C/C++
    int[] a;  // standard java notation 
    

    when declaring multiple array references, we can find difference between them. the following two statements mean same. in fact, it is up to the programmer which one is follow. but the standard java notation is recommended.

    int a[],b[],c[]; // three array references
    int[] a,b,c;  // three array references
    
    0 讨论(0)
  • 2020-11-21 08:17

    No difference.

    Quoting from Sun:

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

    0 讨论(0)
提交回复
热议问题