简体   繁体   English

Java varargs如何在内存中实现

[英]How are Java varargs implemented in the memory

From what I know, local vars and args are stored in the Stack Memory, which includes object references, whereas actual objects are stored in the heap memory. 据我所知,本地var和args存储在堆栈存储器中,其中包括对象引用,而实际对象存储在堆存储器中。 So what exactly happens when you use var-args ? 那么,当您使用var-args时会发生什么呢?

public static int[] test(int... x) {
    return x;
}

public static void main(String[] args) {
    int[] a = test(1,2,3,4,5);
    int[] b = test(6,7,8,9,0);
    System.out.println(a);
    System.out.println(b);
    for (int i : a) {
        System.out.println(i);
    }
    for (int i : b) {
        System.out.println(i);
    }

Here I believe that all the values passed as params to test in x are stored on the stack, hence when we call test(1,2,3,4,5) , we are using up stack space, correspondingly when we call test(6,7,8,9,0) we should be causing memory collision on the stack... but when I run the above, I get the following result. 在这里,我相信所有要作为参数传递给x进行test的值都存储在堆栈中,因此,当我们调用test(1,2,3,4,5) ,我们将耗尽堆栈空间,相应地,当我们调用test(6,7,8,9,0)我们应该在堆栈上引起内存冲突...但是当我运行上面的命令时,我得到以下结果。

[I@2db0f6b2
[I@3cd1f1c8
1
2
3
4
5
6
7
8
9
0

As can be seen, there is no corruption of items in a due to the 2nd call to test which generates b . 可以看出,由于第二次调用test生成b ,因此a的项目没有损坏。 Both seem to be stored differently. 两者似乎存储方式不同。

Does this mean that the params are somehow stored on the heap? 这是否意味着参数以某种方式存储在堆中? Would this mean that any call of the form function(param) translates to the value of param (primitive or memory reference) not necessarily lying on the stack memory? 这是否意味着对任何形式的function(param)调用都将转换为不一定位于堆栈存储器中的param值(原始或内存引用)?

Varags are just a syntactic sugaring on top of arrays - ie, using a int... parameter is the same as an int[] . Varags只是数组顶部的语法加糖-即,使用int...参数与int[]相同。 Like all arrays, the array resides on the heap, and you pass a reference to it down on the stack. 像所有数组一样,该数组驻留在堆上,并在堆栈中向下传递对其的引用。

x... is only a syntactic sugar for a x[] . x...只是x[]的语法糖。 Think its working procedure exactly same as raw array. 认为其工作过程与原始数组完全相同。

The reference itself could be stored on the heap if it is a member of a class or object, or on the stack if it is a local variable in a method. 如果引用本身是类或对象的成员,则可以将其存储在堆中;如果引用是方法中的局部变量,则可以将其存储在堆栈中。 And primitive types can be stored on the heap if they are members of a class or object. 如果原始类型是类或对象的成员,则它们可以存储在堆中。 - Source - 来源

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM