如果我删除一个对象,其中包含另一个由 ArrayList 指向的对象,会发生什么

What happens if i remove an object, which has another object in it that is pointed by an ArrayList

在 Java 中,我有一个名为 Couple 的 Class,它有一个 String 和一个 int 作为 istance 变量。我有一个 ArrayList,它包含 Class Couple 的 istances。一个方法 foo,将新对添加到 ArrayList cop_list。而且,将每条消息添加到另一个 ArrayList,称为 msg_list.

foo(String msg,int id)
{
   Couple cop = new Couple(msg, id);
   //ArrayList<Couple>
   cop_list.add(cop);
   //ArrayList<String>
   msg_list.add(msg);
   ...
}

之后,当我调用 delete(id) 方法时,它应该通过其 id 搜索并删除一对,但它也应该从 msg_list 中删除消息。所以,我的问题是,当我从 cop_list 中删除一个 Couple 对象时,msg_list 中的消息会发生什么变化? msg_list 在我明确删除它之前仍然指向它?字符串对象 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);
}

So, my question is, when i delete a Couple object from the cop_list, what happens to the message in msg_list? msg_list still points to it until i explicitly remove it? String object msg is still on the heap?

是的,您在 msg_list ArrayList 中仍有对字符串的引用,因此该消息仍在内存中。当任何引用指向它时,该对象将不符合垃圾回收条件。

从列表中删除 cop 后,您必须调用 msglist.remove(msg) 来清除消息。
msglist 仍然引用原始 cop 对象中的 String

当您调用 cop_list.remove(cop) 时,msglist 中对 String 的引用仍然存在。所以你必须明确地删除它。