说我做这样的事情:Java的垃圾回收和集合
List<Stuff> methodA() {
List<Stuff> all_the_stuff_to_do = new ArrayList<>();
all_the_stuff_to_do.add(new Stuff("important"));
all_the_stuff_to_do.add(new Stuff("not important"));
return all_the_stuff_to_do;
}
List<Stuff> methodB() {
List<Stuff> important_stuff_to_do = new ArrayList<>();
Stuff important = methodA().get(0);
// at this point Stuff("not important") is not reachable anymore
// since I have no reference to the list that contains it left
important_stuff_to_do.add(important);
return important_stuff_to_do;
}
void methodC() {
... do a happydance ...
List<Stuff> stuff_to_do = methodB();
... look sad because now I got important stuff to do ...
}
*****编辑*****
更好的澄清和简化代码
澄清:
当退出methodA()我得到了一个列表与两个对象的参考东西(“重要”)和东西(“不是我mportant“)
我将对Stuff(”important“)的引用添加到methodB()的列表中。 此时对象东西(“不重要”)无法再到达。 同样在中的列表方法A()不再可用。
但是该列表仍然包含对确实可到达的对象的引用,即材料(“重要”)。
何时会all_the_stuff_to_do列表中清除并当的东西(“不重要”)对象?
在拨打方法A后会直接吗?或者它会在方法B的末尾?或者从来没有,因为它包含对材料(“重要”)的引用直到程序结束仍然有效的对象?
您指的是哪个列表引用? 'all_the_stuff_to_do','important_stuff_to_do'或'stuff_to_do'? – Cypher
“东西(2)”是什么意思?你在打什么方法? –
我想你可能的意思是:'important_stuff_to_do.add(methodA()。get(i));'在methodB中的for循环中 – JimmyJames