Java 如果我删除一个对象,其中有另一个由ArrayList指向的对象,会发生什么
在Java中,我有一个名为Couple的类,它有一个字符串和一个int作为istance变量。我有一个ArrayList,里面有一对班级情侣的名字。一个方法foo,将新夫妇添加到ArrayList cop_列表中。而且,还要将每条消息添加到另一个名为msg_list的ArrayList中Java 如果我删除一个对象,其中有另一个由ArrayList指向的对象,会发生什么,java,arraylist,object-reference,Java,Arraylist,Object Reference,在Java中,我有一个名为Couple的类,它有一个字符串和一个int作为istance变量。我有一个ArrayList,里面有一对班级情侣的名字。一个方法foo,将新夫妇添加到ArrayList cop_列表中。而且,还要将每条消息添加到另一个名为msg_list的ArrayList中 foo(String msg,int id) { Couple cop = new Couple(msg, id); //ArrayList<Couple> cop_list.ad
foo(String msg,int id)
{
Couple cop = new Couple(msg, id);
//ArrayList<Couple>
cop_list.add(cop);
//ArrayList<String>
msg_list.add(msg);
...
}
所以,我的问题是,当我从cop_列表中删除一对对象时,msg_列表中的消息会发生什么变化?msg_列表仍然指向它,直到我明确删除它?字符串对象msg仍在堆上
delete(int id)
{
//search and find the couple, save its msg in a variable
msg = cop.getMsg();
cop_list.remove(cop);
//at this point, can/should i remove msg from msg_list?
//what happens if i call:
msglist.remove(msg);
}
是的,您的
msg_列表中仍有对字符串的引用,因此该消息仍在内存中。当任何引用指向该对象时,该对象将不符合垃圾收集的条件。您必须调用msglist.remove(msg)
以在从列表中删除cop
后清除消息。
msglist
仍然引用原始cop
对象中的String
调用cop\u list.remove(cop)
时,msglist
中对String
的引用仍然保留。因此,您必须明确地将其删除。简单地说:一个对象继续存在,直到其引用计数降至零。一个引用不会因为对同一对象的另一个引用被取消而消失。是的,在没有引用之前,GC不会收集它(这是简化的解释)。当您执行msg=cop.getMsg时,会增加对该对象的引用计数。@laune有点过于简单化-即使循环性质意味着引用计数大于0,也可以收集循环引用。