Alex G
Alex G

Reputation: 747

Will a Java stack pointing to an array use the same amount of memory?

I have a binary tree of Nodes and want to traverse it. The most common method I'm seeing is a Stack, or a LinkedList. I've also seen other methods that don't add each Node to a Stack/List, and seem to take up almost no memory (they use recursion instead to explore each element).

If I make a List<Node> to track each node in the tree, will I be taking up 2*n the amount of memory? Or, because the objects already exist in the tree, will the List only be a bunch of pointers to Node objects (which exist in the Tree), and therefore don't take up twice the memory?

Test Case:

Object objs[] = new Object[40];
/* 
    Initialize the 40 objects here 
*/
List<Object> objTracker = new List<>();
for(int i=0; i<objs.length; i++) {
    objTracker.add(objs[i]);
}

Does this now take up 2x the amount of memory, or do all of the objTrackers just redirect/point to the objects stored in objs?

Upvotes: 0

Views: 39

Answers (2)

jurez
jurez

Reputation: 4657

In Java, stack memory is separate from heap memory. Stack memory is consumed for every method call, but usually this doesn't count as "occupied" memory because it's not managed by GC and because it gets released as soon as the call returns.

In the end, you have to store your objects somewhere. So it's either stack or heap. List and array have comparable space requirements if you're not overallocating their size. In your code, you are not allocating any Nodes - they already exist. You are only allocating space for array / List.

What you are doing with your code is most likely redundant. You can add your elemets to List in the first place. As you have it now, you first store objects in array, then copy them to List. If you have no further uses of objs, then objs will eventually be garbage collected, leaving only objTracker in memory.

Upvotes: 1

Kayaman
Kayaman

Reputation: 73548

You only create a new object when using the new keyword (generally speaking). Since there's no new in objTracker.add(objs[i]);, no new objects are created.

Upvotes: 2

Related Questions