Java中堆栈的提问与回答
来源:互联网 发布:蓝月传奇翅膀升阶数据 编辑:程序博客网 时间:2024/05/25 19:59
原文链接:点击打开链接
问:
class A { int a ; String b; //getters and setters}
1.变量a存储在哪里?
2.为什么堆内存会存在?为什么我们不可以将它存储在栈里?
3.gc什么时候回收对象?栈和对象销毁有联系吗?
答:
1.
堆和栈的最基本的区别是值的生命周期!
栈中的值只存在它们所被创建的函数中,一旦被返回,他将被丢弃。
堆的值存在于堆中。他们被创建于某时刻,在另一时段被摧毁(被gc或手动回收,依赖于运行环境)。
java把基本类型存储在栈中。这样可以使堆栈变小,有助于保持个人的堆栈小,从而使更多的嵌套调用。
对象被创建在堆中,其引用(这又是基本类型)存储在栈中。所以你在堆中创建对象,其包含的一些变量可以在函数被调用后持久保持。
2.
- In the heap, as part of the object, which is referenced by a pointer in the stack. ie. a and b will be stored adjacent to each other.
- Because if all memory were stack memory, it wouldn't be efficient any more. It's good to have a small, fast-access area where we start and have that reference items in the much larger area of memory which remains. However, this is overkill when an object is simply a single primitive which would take up about the same amount of space on the stack as the pointer to it would.
- Yes.
3.
On the heap unless Java allocates the class instance on the stack as an optimization after proving via escape analysis that this will not affect semantics. This is an implementation detail, though, so for all practical purposes except micro-optimization the answer is "on the heap".
Stack memory must be allocated and deallocated in last in first out order. Heap memory can be allocated and deallocated in any order.
When the object is garbage collected, there are no more references pointing to it from the stack. If there were, they'd keep the object alive. Stack primitives aren't garbage collected at all because they're automatically destroyed when the function returns.
- Java中堆栈的提问与回答
- 提问与回答的智慧
- 提问与回答
- 提问与回答 VS2017中C#控制台编程的调试基础示例
- 提问与回答之ClassLoader
- 北岛的《回答》是回答 更是提问
- 提问和回答的智慧
- 提问回答
- 提问与回答之开源协议
- java的堆栈区别(转自 ZangXT 论坛回答)
- 没有回答好老板的提问
- 对CloudFoundry的一些提问和回答
- 回答一位朋友的提问:在Delphi7下如何与DLL共享数据库连接
- 回答一位朋友的提问:在Delphi7下如何与DLL共享数据库连接
- 回答一位朋友的提问:在Delphi7下如何与DLL共享数据库连接
- 回答一位朋友的提问:在Delphi7下如何与DLL共享数据库连接
- 回答一位朋友的提问:在Delphi7下如何与DLL共享数据库连接
- 回答一位朋友的提问:在Delphi7下如何与DLL共享数据库连接
- 备忘录(Memento)
- 安卓bochs运行xp、98、95的详细教程,附上修改过的xp镜像
- 教你9个提升WordPress网站安全性的方法
- dynamic-table-view-cell-height-auto-layout
- 每天专注三件事
- Java中堆栈的提问与回答
- 接口和抽象类有什么区别
- 【test】
- BOOST模板库实现的功能与lua在语言层级提供的支持之比较
- 通过bat脚本修改环境变量并且不用重启立即生效
- 变位词程序的实现
- 线段树成段更新 zoj 1610
- Webdnpro UI控件开发篇 Table控件使用五(Table的单元格使用不同的控件)
- 汇总form表单提交替换按钮为图片