Java 原语数组是存储在堆栈中还是堆中? [英] Is a Java array of primitives stored in stack or heap?

查看:72
本文介绍了Java 原语数组是存储在堆栈中还是堆中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的数组声明:

I have an array declaration like this:

int a[];

这里的a 是一个原始int 类型的数组.这个数组存储在哪里?它存储在堆上还是堆栈上?这是一个原始类型int,所有原始类型都不存储在堆上.

Here a is an array of primitive int type. Where is this array stored? Is it stored on heap or stack? This is a primitve type int, all primitive types are not stored on heap.

推荐答案

正如 gurukulki 所说,它存储在堆上.但是,您的帖子暗示了一种误解,这可能是由于某些善意的人传播了原始人总是生活在堆栈中"的神话.这是不真实的.局部变量在栈上有它们的值,但不是所有的原始变量都是局部的...

As gurukulki said, it's stored on the heap. However, your post suggested a misunderstanding probably due to some well-intentioned person propagating the myth that "primitives always live on the stack". This is untrue. Local variables have their values on the stack, but not all primitive variables are local...

例如,考虑这个:

public class Foo
{
    int value;
}
...

public void someOtherMethod()
{
    Foo f = new Foo();
    ...
}

现在,f.value 住在哪里?神话会暗示它在堆栈上 - 但实际上它是新的 Foo 对象的一部分,并且位于堆1 上.(请注意,f 本身的值是一个引用,并且存在于堆栈中.)

Now, where does f.value live? The myth would suggest it's on the stack - but actually it's part of the new Foo object, and lives on the heap1. (Note that the value of f itself is a reference, and lives on the stack.)

从那里开始,这是一个简单的数组步骤.您可以将数组视为许多变量 - 所以 new int[3] 有点像具有这种形式的类:

From there, it's an easy step to arrays. You can think of an array as just being a lot of variables - so new int[3] is a bit like having a class of this form:

public class ArrayInt3
{
    public readonly int length = 3;
    public int value0;
    public int value1;
    public int value2;
}

<小时>

1 其实比这更复杂.堆栈/堆的区别主要是一个实现细节——我相信一些 JVM,可能是实验性的,可以判断一个对象何时永远不会从方法中逃逸",并且可能会在堆栈上分配整个对象.但是,如果您选择关心,它概念上就在堆上.


1 In fact, it's more complicated than this. The stack/heap distinction is mostly an implementation detail - I believe some JVMs, possibly experimental ones, can tell when an object never "escapes" from a method, and may allocate the whole object on the stack. However, it's conceptually on the heap, if you choose to care.

这篇关于Java 原语数组是存储在堆栈中还是堆中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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