当间接在数组中时,字节原语是否会成为内存中的字节?

Does a byte primitive become a byte in memory when indirectly inside an array?

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

class SomeObject {
    byte iBite;
}

public static void main(String[] args) {
    SomeObject[] objs = ...
}

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

一个字节作为局部变量被实现为一个int,所以需要4个字节。

一个字节作为 class 的 字段(如您的示例)占用 1 个字节的内存,但内存中的 classes 是四舍五入的最多 8 个字节的倍数,例如热点 JVM。也就是说,如果您有一个 class 和多个 byte 字段(或 charshort 字段),这些将更有效地利用内存。

数组类似:每个 byte 将占用 1 个字节,但整个数组将四舍五入为 8 字节的倍数,例如HotSpot JVM。

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

public static class A {
    boolean f;
    byte g;
    int h;
}

我明白了

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

非常清楚地展示了 booleanbyte 以一个字节作为对象字段。

如您所料,charshort 是 2 个字节,intfloat 是 4 个字节,longdouble 是 8 个字节。

解释了 Dalvik 的一些细节,包括目前像 byte 这样的小字段实际上是用 4 个字节实现的。请记住,这些详细信息 将取决于 VM。