Java中递归调用中的局部变量内存

时间:2015-12-18 19:10:08

标签: java variables recursion local

局部变量存储在递归调用的堆栈帧中。

根据我的理解,这意味着每当调用递归方法时,局部变量将具有不同的内存位置(例如1),对于下面代码中的每个递归调用,结果id将是不同的)

我测试了下面的代码,但是我的局部变量结果的内存位置相同,因为1)结果id = 705927765

我不明白为什么?

为什么它具有相同的内存位置?

public class Test {
    static int sum_correct1( int[] A, int n ) {
        int result = 0;

        System.out.println("1) result id = " + System.identityHashCode( result ));

        if( n < 0) 
            result = 0;
        else {
            int smallResult = sum_correct1( A, n - 1 );
            System.out.println("\n2) A[" + n + "] = " + A[n] + " smallResult id = " + System.identityHashCode( smallResult ));
            result = smallResult + A[n];
            System.out.println("3) result id = " + System.identityHashCode( result ));
        }
        return result;
    }

    public static void main( String[] args ) {
        int[] A = {1, 2, 3, 4, 5};
        System.out.println( "sum correct 1 = " + sum_correct1(A, A.length - 1) ) ;
    }
}


1) result id = 705927765
1) result id = 705927765
1) result id = 705927765
1) result id = 705927765
1) result id = 705927765
1) result id = 705927765

2) A[0] = 1 smallResult id = 705927765
3) result id = 366712642

2) A[1] = 2 smallResult id = 366712642
3) result id = 1829164700

2) A[2] = 3 smallResult id = 1829164700
3) result id = 2018699554

2) A[3] = 4 smallResult id = 2018699554
3) result id = 1311053135

2) A[4] = 5 smallResult id = 1311053135
3) result id = 118352462
sum correct 1 = 15

1 个答案:

答案 0 :(得分:0)

将基本类型传递给System.identityHashCode()方法时,变量将被包装到适当的对象中(在本例中为java.lang.Integer)。 JVM尝试为小整数缓存Integer包装器(我认为是-1024 - 1023),因此它总是会产生相同的对象。

尝试修改代码以获得更高的数字,并且您将获得不同的身份哈希码。

相关问题