Home Segments Top Top Previous Next

527: Sidetrip

Many programmers find it helpful—albeit not absolutely necessary—to understand, in general terms, how arrays are implemented.

In Java, integer arrays contain a length instance variable and 4 bytes of memory for every int instance in the array. The 4-byte chunks are arranged consecutively in memory. If you want to know the address of the first byte occupied by the nth integer, you add the address of the first byte of the zeroth integer to 4 * n.

*---------------------------------------------------------------------* 
|                                                                     | 
|    *-- Memory for length instance variable                          | 
|    v                                                                | 
|  -----------------                                                  | 
|  *---*---*---*---*                                                  | 
|  |   |   |   |   |                                                  | 
|  *---*---*---*---*       Memory for four int instances --*          | 
|                                                          |          | 
|          *---------------*---------------*---------------*          | 
|          |               |               |               |          | 
|          v               v               v               v          | 
|   --------------- --------------- --------------- ---------------   | 
|  *---*---*---*---*---*---*---*---*---*---*---*---*---*---*---*---*  | 
|  |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |  |  
|  *---*---*---*---*---*---*---*---*---*---*---*---*---*---*---*---*  | 
|                                                                     | 
*---------------------------------------------------------------------*