如何存储在Java内存静态数组? [英] How are static arrays stored in Java memory?

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

问题描述

因此​​,在如C语言,存储器被分成5个不同的部分:操作系统内核,文本段,静态存储器,动态存储器,和堆栈。事情是这样的:

So in a language like C, memory is separated into 5 different parts: OS Kernel, text segment, static memory, dynamic memory, and the stack. Something like this:

如果我们宣布在C静态数组,你必须指定它的大小事先后,将被永远定。该计划将分配足够的内存阵列和坚持在静态数据段的预期。

If we declared a static array in C, you had to specify it's size beforehand after that would be fixed forevermore. The program would allocate enough memory for the array and stick it in the static data segment as expected.

不过,我注意到,在Java中,你可以做这样的事情:

However I noticed that in Java, you could do something like this:

public class Test {
        static int[] a = new int[1];

        public static void main( String[] args ) {
                a = new int[2];
        }
} 

和一切都会按照您所期望的。我的问题是,为什么在Java中这项工作?

and everything would work as you'd expect. My question is, why does this work in Java?

编辑:所以的共识是,一个 INT [] 在Java中是比较类似的行为作为int * 在C.因此,作​​为一个跟进的问题,有没有什么办法来分配静态存储器阵列在Java中(如果没有,为什么不呢)?这是不是给这些数组更快的访问?
EDIT2:^这是现在一个新的问题:<一href=\"http://stackoverflow.com/questions/6655338/where-are-static-class-variables-stored-in-memory\">Where存储在内存中的静态类变量?

So the consensus is that an int[] in Java is acts more similarly to an int* in C. So as a follow up question, is there any way to allocate arrays in static memory in Java (if no, why not)? Wouldn't this provide quicker access to such arrays? ^ this is in a new question now: Where are static class variables stored in memory?

推荐答案

在Java中,你使用这个词的任何时间,该对象的内存是在堆上分配和返回引用。这也是数组如此。在 INT []一个仅为参考新INT [1] 。当你做新INT [2] ,一个新的数组分配,指着一个。在需要的时候旧的阵列将被垃圾收集。

In java any time you use the word new, memory for that object is allocated on the heap and a reference is returned. This is also true for arrays. The int[] a is just the reference to new int[1]. When you do new int[2], a new array is allocated and pointed to a. The old array will be garbage collected when needed.

这篇关于如何存储在Java内存静态数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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