java动态内存分配?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2532767/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 08:55:36  来源:igfitidea点击:

java dynamic memory allocation?

javamemory-managementinstantiation

提问by JavaUser

Why is an object initialization using the newkeyword called dynamic memory allocation, since compile time itself we need to know the memory needed for that object.

为什么使用new称为动态内存分配的关键字进行对象初始化,因为编译时本身我们需要知道该对象所需的内存。

Also please explain what happens when you do ClassA object = new ClassA();in heapand stack.

另请解释ClassA object = new ClassA();heapstack 中执行时会发生什么。

回答by Donal Fellows

AllJava objects are dynamically allocated. You're always passing around references to them. This is how the language is designed. When you do:

所有Java 对象都是动态分配的。你总是传递对它们的引用。这就是语言的设计方式。当你这样做时:

ClassA obj = new ClassA();

Then the object is allocated on the heap and a reference to it is stored on the stack (assuming that's inside a method, of course). What this means is that you can always pass objects about without worrying about where they are stored.

然后在堆上分配对象,并将对它的引用存储在堆栈中(当然,假设它在方法内部)。这意味着您始终可以传递对象而不必担心它们的存储位置。

回答by Brian Agnew

It's dynamic since you don't know whenit needs allocating - you allocate upon demand.

它是动态的,因为你不知道它什么时候需要分配——你按需分配。

Note also that you know how much memory that object requires, but not how much that object's members require. This may only be determinable at run time (e.g. an array of variable size).

另请注意,您知道该对象需要多少内存,但不知道该对象的成员需要多少内存。这可能只能在运行时确定(例如可变大小的数组)。

回答by Asad Mukhtar

If you have a class of JMathand you want to get all its objects on runtime(Dynamically allocation) then you just wrote

如果你有一个类JMath并且你想在运行时获取它的所有对象(动态分配)那么你就写了

ArrayList<JMath> J = new ArrayList<JMath> ();