Initializing array with values - should I explicitly instance the class or not?

后端 未结 3 708
一整个雨季
一整个雨季 2020-12-17 10:28

I often see arrays being initialized like this:

String[] array = new String[] { \"foo\", \"bar\", \"baz\" };

But reading the Language Basic

相关标签:
3条回答
  • 2020-12-17 10:48

    Since arrays are intended to be mutable, it makes sense that each one is a new instance

    String[] array1 = { "foo", "bar", "baz" };
    String[] array2 = { "foo", "bar", "baz" };
    

    i.e. modifying array1 won't affect array2.

    0 讨论(0)
  • 2020-12-17 11:01

    Is there any difference between these?

    There is no difference in the end result. However, as per the JLS § 10.6, you cannot use the array initializer synax in every context.

    An array initializer may be specified in a declaration (§8.3, §9.3, §14.4), or as part of an array creation expression (§15.10), to create an array and provide some initial values.

    0 讨论(0)
  • 2020-12-17 11:03

    The two methods are equivalent. Note, however, that the concise syntax can only be used in variable declarations. Outside variable declarations you have to use the verbose syntax:

        String[] array;
        array = new String[] { "foo", "bar", "baz" }; // OK
    
        String[] array2;
        array2 = { "foo", "bar", "baz" };             // ERROR
    

    For further discussion, see this answer.

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