How are Integer arrays stored internally, in the JVM?

后端 未结 5 830
星月不相逢
星月不相逢 2020-12-20 23:22

An array of ints in java is stored as a block of 32-bit values in memory. How is an array of Integer objects stored? i.e.

int[] vs. Integer[]
5条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-20 23:59

    The reason that Integer can be null, whereas int cannot, is because Integer is a full-fledged Java object, with all of the overhead that includes. There's value in this since you can write

    Integer foo = new Integer();
    foo = null; 
    

    which is good for saying that foo will have a value, but it doesn't yet.

    Another difference is that int performs no overflow calculation. For instance,

    int bar = Integer.MAX_VALUE;
    bar++;
    

    will merrily increment bar and you end up with a very negative number, which is probably not what you intended in the first place.

    foo = Integer.MAX_VALUE;
    foo++;
    

    will complain, which I think would be better behavior.

    One last point is that Integer, being a Java object, carries with it the space overhead of an object. I think that someone else may need to chime in here, but I believe that every object consumes 12 bytes for overhead, and then the space for the data storage itself. If you're after performance and space, I wonder whether Integer is the right solution.

提交回复
热议问题