-2

In Java, I have a Class called Couple which has a String and an int as istance variables. And i have an ArrayList which holds istances of Class Couple. A method foo, adds new couples to the ArrayList cop_list. But also, add every message to another ArrayList, called 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);
   ...
}

After that, When i call a delete(id) method, it should search and remove a couple by its id, but it should also remove the message from msg_list. 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?

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);
}
user3717434
  • 215
  • 4
  • 19
  • 1
    Simply put: an object continues to live until its reference count drops to zero. One reference doesn't disappear due to another reference to the same object being nullified. – laune Jun 01 '15 at 16:23
  • 1
    Yes, it will be not collected by GC until there are no references (it is simplified explanation). When you do msg = cop.getMsg you increase reference count to that object. – edmarisov Jun 01 '15 at 16:25
  • 1
    @laune A bit oversimplified - circular references can be collected even though the circular nature means the refcount is > 0. – Thorn G Jun 01 '15 at 16:34

2 Answers2

1

You will have to call msglist.remove(msg) to clear message after removing cop from the list.
The msglist still have reference to String from original cop object.

When you call cop_list.remove(cop) the reference to String in msglist still stays. So you will have to remove it explicitly.

hitz
  • 1,100
  • 8
  • 12
0

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?

Yes, you still have a reference to the String in your msg_list ArrayList, so that message is still in memory. The object won't be eligible for garbage collection while any references point to it.

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880