分配的变量引用在哪里,在堆栈中还是在堆中? [英] Where is allocated variable reference, in stack or in the heap?

查看:29
本文介绍了分配的变量引用在哪里,在堆栈中还是在堆中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有个问题

例如,当我在方法中声明一个变量时会发生什么.

<前>无效我的方法(){Ship myShip = new Ship();}

myShip 引用在哪里分配,在堆栈中还是在堆中?

我在堆栈中思考,但我很困惑,因为我正在阅读 J2ME 游戏编程书"Java 类被实例化到 Java 堆上"

所有的java类?

提前致谢

解决方案

myShip 是对 Ship 对象的引用,myShip 已打开方法调用栈,简称栈".当一个方法被调用时,一个内存块被推到堆栈的顶部,该内存块有空间用于所有基元(int、float、boolean等)和方法的对象引用,其中包括方法参数.堆是为实际对象分配内存的地方.

所以 myShip 在堆栈上,Ship 对象在堆上.

注意每个线程都有自己的堆栈,但共享堆.

I have a question

What happend when I declare a variable inside a method, for example.

void myMethod() {
    Ship myShip = new Ship();
}

Where is allocated myShip reference, in stack or in the heap ?

I think in stack but I'm confused because I was reading in J2ME Game Programming book "Java classes are instantiated onto the Java heap"

All java clases ?

Thanks in advance

解决方案

myShip is a reference to a Ship object, myShip is on the method call stack, which is referred to as "the stack". When a method is called a block of memory is pushed onto the top the stack, that memory block has space for all primitives (int, float, boolean etc) and object references of the method, which includes the method parameters. The heap is where the memory for the actual objects is allocated.

So myShip is on the stack and the Ship object is on the heap.

Note each thread has its own stack but share the heap.

这篇关于分配的变量引用在哪里,在堆栈中还是在堆中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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