Java List/Array 清单说明
Java List/Array List clarification
如果有人能解释这两种类型的数组初始化之间的区别,那就太好了:
classListReturn
中有一个静态方法getList()
,调用时return是ArrayList<Some_Custom_Object>
。
在调用class时,我可以通过以下两种方式调用函数:
List<Some_Custom_Object> listFromCall = new ArrayList<Some_Custom_Object>();
listFromCall=ListReturn.getList();//works completely fine
List<Some_Custom_Object> listFromCall = ListReturn.getList();//Works completely fine
我的问题是,在第二种情况下,我们不需要初始化或实例化 listFromCall 对象吗?我们可以直接将方法中的 return 值分配给未初始化的 List/ArrayList 吗?对象?
有人可以解释一下这里发生了什么吗?
谢谢
如果在写入之前读取变量,则只需初始化变量。
如果您写入未初始化的变量,计算机不会在意,因为您正在使用 ListReturn.getList()
中的 return 值对其进行初始化。
事实上,如果对象变量将在使用前被覆盖,则您不应该不必要地将对象变量初始化为 null
以外的任何内容。否则,您会无缘无故地创建和垃圾收集一个额外的对象。
让我们一一讨论,
第一种方式:
List<Some_Custom_Object> listFromCall = new ArrayList<Some_Custom_Object>();
意思是,类似的,
listFromCall=ListReturn.getList();//works completely fine
it will reflect on listFromCall's value assignment, see below image for
deeper understanding,
Here, completion of both statement, total either 2-object created(1
will eligible for garbage collection after second created and assign)
or 1-object created (which will become eligible for garbage collection
and assign null to reference variable)
你的第二种方式:
现在如果你也这样做,
2. List<Some_Custom_Object> listFromCall = ListReturn.getList();//Works completely fine
然后会出现类似的东西,
So, here either 1-object(of ArrayList)
will created on heap or not.
如果有人能解释这两种类型的数组初始化之间的区别,那就太好了:
classListReturn
中有一个静态方法getList()
,调用时return是ArrayList<Some_Custom_Object>
。
在调用class时,我可以通过以下两种方式调用函数:
List<Some_Custom_Object> listFromCall = new ArrayList<Some_Custom_Object>();
listFromCall=ListReturn.getList();//works completely fine
List<Some_Custom_Object> listFromCall = ListReturn.getList();//Works completely fine
我的问题是,在第二种情况下,我们不需要初始化或实例化 listFromCall 对象吗?我们可以直接将方法中的 return 值分配给未初始化的 List/ArrayList 吗?对象?
有人可以解释一下这里发生了什么吗?
谢谢
如果在写入之前读取变量,则只需初始化变量。
如果您写入未初始化的变量,计算机不会在意,因为您正在使用 ListReturn.getList()
中的 return 值对其进行初始化。
事实上,如果对象变量将在使用前被覆盖,则您不应该不必要地将对象变量初始化为 null
以外的任何内容。否则,您会无缘无故地创建和垃圾收集一个额外的对象。
让我们一一讨论,
第一种方式:
List<Some_Custom_Object> listFromCall = new ArrayList<Some_Custom_Object>();
意思是,类似的,
listFromCall=ListReturn.getList();//works completely fine
it will reflect on listFromCall's value assignment, see below image for deeper understanding,
Here, completion of both statement, total either 2-object created(1 will eligible for garbage collection after second created and assign) or 1-object created (which will become eligible for garbage collection and assign null to reference variable)
你的第二种方式:
现在如果你也这样做,
2. List<Some_Custom_Object> listFromCall = ListReturn.getList();//Works completely fine
然后会出现类似的东西,
So, here either
1-object(of ArrayList)
will created on heap or not.