Java: int array initializes with nonzero elements

前端 未结 2 1430
暖寄归人
暖寄归人 2021-01-29 23:37

According to the JLS, an int array should be filled by zeros just after initialization. However, I am faced with a situation where it is not. Such a behavior occurs

2条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-30 00:27

    I made some change in your code. It's not a problem of Integer overflow. See the code, it throws an exception at runtime

        int[] a;
        int n = 0;
        for (int i = 0; i < 100000000; ++i) {
            a = new int[10];
            for (int f : a) {
                if (f != 0) {
                    throw new RuntimeException("Array just after allocation: " + Arrays.toString(a));
                }
            }
            for (int ii = 0, len = a.length; ii < len; ii++)
                a[ii] = 0;
            for (int j = 0; j < a.length; ++j)
                a[j] = Integer.MAX_VALUE - 1;
            for (int j = 0; j < a.length; ++j)
                n++;
        }
    

提交回复
热议问题