Is there any way to create a primitive array without initialization?

前端 未结 4 1982
轮回少年
轮回少年 2020-12-10 13:07

As we know Java always initialises arrays upon creation. I.e. new int[1000000] always returns an array with all elements = 0. I understand that it\'s a must for

4条回答
  •  -上瘾入骨i
    2020-12-10 13:53

    I'm going to move this to an answer because it probably should be.

    An "Array" in java is not what you think it is. It's not just a pointer to a chunk of contiguous memory on the stack or heap.

    An Array in Java is an Object just like everything else (except primitives) and is on the heap. When you call new int[100000] you're creating a new object just like every other object, and it gets initialized, etc.

    The JLS provides all the specific info about this:

    http://docs.oracle.com/javase/specs/jls/se5.0/html/arrays.html

    So, no. You can't avoid "initializing" an array. That's just not how Java works. There's simply no such thing as uninitialized heap memory; many people call that a "feature" as it prevents you from accessing uninitialized memory.

提交回复
热议问题