What is the memoy size of a Java object array after it has been created?

后端 未结 2 1744
再見小時候
再見小時候 2021-01-05 07:05

This probably doesn\'t even need asking, but I want to make sure I\'m right on this. When you create an array of any object in Java like so:

Object[] objArr         


        
相关标签:
2条回答
  • 2021-01-05 07:40

    The null references do "take up space" -- the array's memory is allocated up-front in one chunk, and zeroed (to make all of the contents null references). As an exercise, try allocating a huge array, one that will take up more space than your JVM's memory limit. The program should immediately terminate with an out of memory error.

    0 讨论(0)
  • 2021-01-05 07:46

    I think this will be helpful to you

    public static void main(String[] args) {
            Runtime r = Runtime.getRuntime();
            System.gc();
            System.out.println("Before " + r.freeMemory());
            Object[] objArr = new Object[10];
            System.out.println("After " + r.freeMemory());
            objArr[0] = new Integer(3);
            System.gc();
            System.out.println("After Integer Assigned " + r.freeMemory());
        }
    

    Output

    Before 15996360
    After 15996360
    After Integer Assigned 16087144
    
    0 讨论(0)
提交回复
热议问题