Java可以在堆栈上分配列表吗? [英] Can Java allocate a list on stack?

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

问题描述

每当我在java中启动列表时,我都会这样做

Every time when I initiate a list in java, I will do

List<Integer> list = new LinkedList<>();

我假设这将在堆上分配列表。不知道我是否可以在堆栈上分配列表?

I assume that this will allocate the list on heap. Wonder if there's anyway that I could allocate the list on stack?

推荐答案

所有对象,包括它们各自的属性,都存储在堆。

All objects, including their individual attributes, are stored on the heap.

所有局部变量及其参数都存储在堆栈中,因为它们包含原始值或引用。

All local variables, and their arguments, are stored on the stack because they contain primitive values or references.

但是,在特殊情况下,java虚拟机可能会执行转义分析并决定分配对象(包括 LinkedList )在堆栈上,但这通常不会发生并且不是主要问题。

However, in special cases, the java virtual machine may perform escape analysis and decide to allocate objects (including your LinkedList) on a stack, but this normally doesn't happen and isn't a major concern.

作为一般规则,如果在堆栈上分配对象,当你调用引用它的函数时,它将获得该对象的副本。相反,如果在堆上分配对象,当您将指针传递给对象时,您将获得指针的副本(指向堆上的同一对象。)

As a general rule, if you allocate an object on a stack you will get a copy of the object when you call a function that refers to it. In contrast, if you allocate an object on the heap, when you pass the pointer to the object you will get a copy of the pointer (which points to the very same object on the heap.)

这篇关于Java可以在堆栈上分配列表吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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