Difference in Array initialization

后端 未结 5 1057
故里飘歌
故里飘歌 2021-01-20 23:40

While looking over a source file, i saw two ways of array initialization. I wonder is there a difference between

int[] value = new int[0];

and<

相关标签:
5条回答
  • 2021-01-21 00:29

    No, there's no difference.

    Both create an array with 0 elements.

    0 讨论(0)
  • 2021-01-21 00:38

    Actually there is no difference. It's Syntactic sugar in java array declaration.

    The first type declaration is less confusing, at least for me :).

    Note: I'm not sure why you given the length as zero while declaring.

    If possible, go through https://stackoverflow.com/a/19558179/1927832 for some advantages over another.

    0 讨论(0)
  • 2021-01-21 00:38

    There is absolutely no difference.

    int[] a = new int[0] is to be preferred because it shows the intention of creating an empty array.

    0 讨论(0)
  • 2021-01-21 00:40

    Now the proof (and an exercise):

    Create two classes, each containing one declaration. Compile them to get .class files.
    On each of the two created files, do:

    javap -c yourClass
    

    To see the bytecode.

    Now you can answer your own question.

    0 讨论(0)
  • 2021-01-21 00:42

    There is no difference, although in the second case you have redundant [].

    Personally I prefer to use int[] value_next = {} to create an empty array.

    In my opinion, int[] value = new int[0]; can, on rapid reading, look like you're creating an array with one element in it with initial value of 0. During a 3am debugging session I really appreciate clarity.

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