• Post Reply Bookmark Topic Watch Topic
  • New Topic

Question on linked list and object references  RSS feed

 
Ameena Rupam
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I had a question about data structures. For the insert method of a linked list, the 'node' object is declared in the insert method. So doesn't the 'node' get destroyed as soon as the closing brace of the insert method is encountered? How do all the nodes continue to occupy memory? Because I am aware this is what happens with variables.
 
fred rosenberger
lowercase baba
Bartender
Posts: 12563
49
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch!

First, I split your question off to its own topic. We have plenty of room here for as many topics as you like, so please feel free to create your own when you have a new question.

Next, I'm not sure the object is created in the insert method of a linked list...I suppose it COULD be, but I don't think it HAS to be.

In any case, remember that variables hold references to objects. It's similar to when you construct a house, you write the address down on a slip of paper. Or maybe a better way is you bury some treasure, and you create a map on how to find it again. So when the node is created, the actual object is buried off in memory somewhere, and your variable holds the reference (i.e. the map) so you can find it again.

You can then pass a copy of the map around. In the linked list scenario, you copy the reference/map when you pass it in to a method - so there could now be two things pointing to the object. Even if you destroy one (i.e. when you leave the method), as long as SOMEONE/SOMETHING has a copy of the reference/map, Java knows the object off in memory needs to be kept around.

Only once every reference to the object is gone will Java consider deleting it from memory (ok...I'm skipping a few details here, but generally speaking this is true).
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!