且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Java中静态初始化和动态初始化之间的区别是什么?

更新时间:2022-11-23 16:42:52

初始值设定项 {1,2} 是 new int [] {1,2} 。此简写只能用作 int [] 1 类型变量的初始化程序。例如,以下工作原理:

The initializer {1,2} is shorthand for new int[] {1,2}. This shorthand can only be used as an initializer for a variable of type int[].1 For instance, while the following works:

int arr[] = {1,2};

这不是:

int arr[];
arr = {1,2}; // ERROR

相反,您需要使用:

int arr[];
arr = new int[] {1,2};

同样,您可以使用:

Object o3 = new int[] {1,2};

P.S。以上内容适用于 static 以及实例字段,也适用于局部变量。 Java没有静态与动态初始化这样的区别。这是更多的C ++术语。

P.S. The above applies to static as well as instance fields, and also to local variables. Java doesn't have such a distinction as "static vs. dynamic initialization". That's more C++ terminology.

  1 嗯,它也可能是类型的变量byte [] long []
float [] Integer [] 等,文字 1 2 分配兼容。请参阅 Java语言的第10.6节规范

 1Well, it could also be for a variable of type byte[], long[], float[], Integer[], etc., for which the literals 1 and 2 are assignment compatible. See the Section 10.6 of the Java Language Specification.