Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
387 views
in Technique[技术] by (71.8m points)

heap memory - Can Java allocate a list on stack?

Every time when I initiate a list in java, I will do

List<Integer> list = new LinkedList<>();

I assume that this will allocate the list on heap. Wonder if there's anyway that I could allocate the list on stack?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

All objects, including their individual attributes, are stored on the heap.

All local variables, and their arguments, are stored on the stack because they contain primitive values or references.

However, in special cases, the java virtual machine may perform escape analysis and decide to allocate objects (including your LinkedList) on a stack, but this normally doesn't happen and isn't a major concern.

As a general rule, if you allocate an object on a stack you will get a copy of the object when you call a function that refers to it. In contrast, if you allocate an object on the heap, when you pass the pointer to the object you will get a copy of the pointer (which points to the very same object on the heap.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...