Local VS global variables in Java

萝らか妹 提交于 2019-11-29 08:43:24

This is mixing up variables and objects, newElement is indeed a local variable and it is lost after the method ends, but the reference points to an object. An object is eligable for garbage collection if no references (variables) point to it. In this case temporarily newElement and firstElement both pointed to it. It lost newElement when the method exited but firstElement still points to it, as does lastElement so it isn't eligable for garbage collection.

Or in other words: A variable refers to an object, it is not the object itself.

An analogy:

  • variable: piece of paper you can write an address on
  • object: house
  • garbage collector: demolitions crew

I build a house and write it's address on a scrap of paper so you can get there, I pass that scrap of paper to you, you write the address from the scrap of paper into your address book, you throw away the scrap of paper.

The demolitions crew checks whether anyone is still using a house by seeing if anyone still holds its address. Even though you threw away the scrap of paper you still have the address in your address book so the house is still being used and is not demolished

newElement is just a reference to an object created in memory.

firstElement then holds a reference to the same object.

The reference newElement is indeed a local variable, but the object referred to by the reference is then also referred to by another reference, i.e. firstElement. So after the addDataPacket() method completes, the newElement reference no longer exists, but the object that it referred to still exists in memory and that object is referred to by firstElement.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!