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

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

问题描述

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

I have an array declaration like this:

int a[];

下面 A 是原始数组 INT 键入。在哪里存储这个数组?难道是存储在堆或栈?这是一个primitve键入 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 生活?神话建议它的堆栈上 - 但实际上它是新的对象的一部分,住在堆上 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.)

从那里,这是一个简单的步骤来阵列。你可以把一个数组作为摆明​​了很多变数 - 这样新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天全站免登陆