Difference between int[] array and int array[]

前端 未结 25 2828
轻奢々
轻奢々 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:05

    There is no difference, but Sun recommends putting it next to the type as explained here

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

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

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

    No, these are the same. However

    byte[] rowvector, colvector, matrix[];
    

    is equivalent to:

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

    Taken from Java Specification. That means that

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

    are different. I would not recommend either of these multiple declarations. Easiest to read would (probably) be:

    int[] a;
    int[] b;
    
    0 讨论(0)
  • 2020-11-21 08:07

    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

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

    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.

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

    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.

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