Java中静态初始化和动态初始化之间的区别是什么? [英] what's the differences between static initialization and dynamic initialization in Java?
问题描述
最近当我在LeetCode上做一些练习时,我发现了一些技巧解决方案。它使用Object o来引用数组 Object o = new Object [] {null,null};
,我想也许是因为在java中一切都是object.But当我尝试这种方式时,它出错了。 Object o3 = {1,2};
所以我尝试各种方式初始化数组,我想看到差异,比如这些
Recently when I do some practice on LeetCode,I find some trick solution.It use an Object o to reference an arrayObject o = new Object[]{null,null};
,I guess maybe it's because in java everything is object.But when I tried this way,it went wrong.Object o3 = {1,2};
So I tried every way to initialization a array and I want to see the difference,like these
int arr[] = {1,2};
Object o = arr;
Object o1 = new int[2];
Object o2 = new int[]{1,2};
Object o3 = {1,2};
只有o3会编译错误。我不知道是不是因为初始化的方式。我知道当我使用静态初始化时它将首先分配内存,当使用动态初始化时它不会。它们之间的任何其他差异会导致此错误吗?当我使用new创建数组时。它在jvm中做了什么?提前感谢。
Only the o3 will compile an error.I don't know if it's because the way of initialization.I know when I use static initialization it will allocate memory first,when use dynamic initialization it will not.Any other differences between them cause this error?When I use new to create a array.what did it do in jvm?Thanks in advance.
推荐答案
初始值设定项 {1,2}
是<$的简写c $ c> 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.
这篇关于Java中静态初始化和动态初始化之间的区别是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!