您可以使用jol來了解對象的確切佈局。這是程序的爲你的Node類的輸出(在Oracle JDK 1.8.0_121 64位):
# 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.example.Node object internals:
OFFSET SIZE TYPE DESCRIPTION VALUE
0 4 (object header) 01 00 00 00 (00000001 00000000 00000000 00000000) (1)
4 4 (object header) 00 00 00 00 (00000000 00000000 00000000 00000000) (0)
8 4 (object header) 70 22 01 f8 (01110000 00100010 00000001 11111000) (-134143376)
12 4 int Node.val 0
16 1 boolean Node.flag false
17 3 (alignment/padding gap) N/A
20 4 Node Node.left null
24 4 Node Node.right null
28 4 (loss due to the next object alignment)
Instance size: 32 bytes
Space losses: 3 bytes internal + 4 bytes external = 7 bytes total
所以,對準是8個字節。對於32位JVM,它將是4個字節。
請注意,這是平臺特定的。你不應該太依賴這些信息。
此外,類型的大小不是類型的真正大小。一個類型的大小不僅僅包含單純的元素。你有方法,構造函數,頭文件,成員類型有自己的開銷,'''''文字,...實例的大小可以變化很大,從零字節到一個寄存器或兩個到幾個字節,包含組合實例的堆上的完整計算大小,具體取決於運行時條件。 –