使用堆栈空间的 Java 数组 [英] Java array using stack space

查看:49
本文介绍了使用堆栈空间的 Java 数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是声明Java数组的常用方法:

This is the usual way for declare a Java array:

int[] arr = new int[100];

但是这个数组正在使用堆空间.有没有办法像c++一样使用堆栈空间声明数组?

But this array is using heap space. Is there a way we can declare an array using stack space like c++?

推荐答案

总之,没有.

存储在堆栈中的唯一变量是基元和对象引用.在您的示例中,arr 引用存储在堆栈中,但它引用了堆上的数据.

The only variables that are stored on the stack are primitives and object references. In your example, the arr reference is stored on the stack, but it references data that is on the heap.

如果您从 C++ 提出这个问题是因为您想确保您的记忆被清理干净,请阅读 垃圾收集.简而言之,Java 会自动清理堆中的内存以及堆栈中的内存.

If you're asking this question coming from C++ because you want to be sure your memory is cleaned up, read about garbage collection. In short, Java automatically takes care of cleaning up memory in the heap as well as memory on the stack.

这篇关于使用堆栈空间的 Java 数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆