哪一个在堆栈上? [英] Which goes on the stack or heap?

查看:91
本文介绍了哪一个在堆栈上?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做一些研究,遇到一个问题,要求显示以下代码的正确内存图:

I am doing some studying and I came across a question that asks to show the correct memory diagram of the following code:

int [] d1 = new int[5];
d1[0] = 3;

Integer [] d2 = new Integer[5];
d2[0] = new Integer(3);

ArrayList d3 = new ArrayList();
d3.add(3);

这是我尝试的存储图,但这可能是错误的:

Here is my attempt at a memory diagram, but it may be incorrect:

我了解对象,实例变量和新"实例之类的东西都在堆上,而局部变量和原始类型之类的东西都在堆栈上,但是对于数组类型,我仍然感到困惑.

I understand things like objects, instance variables, and "new" instances are all on the heap and things such as local variables and primitive types are on the stack, but I'm still confused when it comes to array types.

感谢您的帮助.

推荐答案

Java上的任何对象都位于堆中.

Any Object on Java lives on heap.

在Java中,数组也是一个对象,因此数组对象存在于堆中.

In Java Array is also an Object and hence array Object lives on heap.

说明:-

撰写时

int a=new int[5],

(新int [5])部分创建了对象,因此位于堆上.

the (new int[5]) part creates object and hence lives on heap.

Integer x=new Integer(10000)

也是一个对象(请记住,新的操作员将始终创建新的对象).

is also an Object(remember new Operator will always create new Object).

因此,当你变瘦时,

Integer [] d2 = new Integer[5];

它是整数对象的数组.

就ArrayList而言,它也是一个类,但是它包装了数组Object并为其添加了动态内存. 所以,

As far as ArrayList is considered it is also a class but it wraps array Object and adds dynamic memory to it. So,

ArrayList d3 = new ArrayList();

再次创建对象并因此驻留在堆上.

again creates Object and hence live on heap.

将ArrayList类视为:

Consider ArrayList class as:

class ArrayList{
    int index=0;
    Object[] obj=new Object['some integer value (depends on JVM)'];
    public void add(Object o){
        obj[index]=o;
        index++;
    }
    //other methods
}

所以当你写的时候 d3.add(5)实际上是d3.add(new Integer(5))被调用.

so when you write d3.add(5) actually d3.add(new Integer(5)) is being called.

记住一个黄金法则: 在Java中,无论您创建的任何对象都在HEAP上运行,而它们的引用则在堆栈上运行.

Remember one golden rule: In java whatever Object you create live on HEAP and their reference live on stack.

作为对象的数组证明:-

Proof of array being object:-

int[] a={4,3,1,2};
System.out.println(a instanceof Object);

//打印为真

这篇关于哪一个在堆栈上?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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