间接在数组内部时,字节原语是否会在内存中变成字节?

Str*_*324 3 java memory arrays bytearray

我听说一个字节本身会占用4个字节的内存,而字节数组内部的一个字节会占用1个字节,但是数组内对象的字节成员变量呢?

class SomeObject {
    byte iBite;
}

public static void main(String[] args) {
    SomeObject[] objs = ...
}
Run Code Online (Sandbox Code Playgroud)

每个SomeObject的iBite变量在内存中是否只有1个字节?

Lou*_*man 5

一个字节作为局部变量实现为int,因此需要4个字节。

字节作为字段(如您的示例)占用1字节的内存,但是内存中的类在例如HotSpot JVM上被四舍五入为8字节的倍数。这就是说,如果你有多个类byte字段(或charshort域),这些都会更有效地利用内存。

数组是相似的:每个数组byte将占用1个字节,但在例如HotSpot JVM上,数组作为一个整体将被四舍五入为8字节的倍数。

您可以使用http://openjdk.java.net/projects/code-tools/jol/进行手动试验。如果您使用它,例如

public static class A {
    boolean f;
    byte g;
    int h;
}
Run Code Online (Sandbox Code Playgroud)

我懂了

Running 64-bit HotSpot VM.
Using compressed oop with 3-bit shift.
Using compressed klass with 3-bit shift.
Objects are 8 bytes aligned.
Field sizes by type: 4, 1, 1, 2, 2, 4, 4, 8, 8 [bytes]
Array element sizes: 4, 1, 1, 2, 2, 4, 4, 8, 8 [bytes]

org.openjdk.jol.samples.JOLSample_01_Basic.A object internals:
 OFFSET  SIZE    TYPE DESCRIPTION                    VALUE
      0    12         (object header)                N/A
     12     4     int A.h                            N/A
     16     1 boolean A.f                            N/A
     17     1    byte A.g                            N/A
     18     6         (loss due to the next object alignment)
Instance size: 24 bytes (estimated, the sample instance is not available)
Space losses: 0 bytes internal + 6 bytes external = 6 bytes total
Run Code Online (Sandbox Code Playgroud)

它显示得很清楚,boolean并且byte以一个字节作为对象字段。

正如你所预料,charshort2个字节,int并且float是4个字节,long并且double是8个字节。

/sf/answers/1034757881/解释了有关Dalvik的一些细节,包括当前的小字段byte(实际上是用4个字节实现的)。请记住,这些细节将成为虚拟机相关的。