Does an array object explicitly contain the indexes?

后端 未结 9 2067
时光取名叫无心
时光取名叫无心 2021-02-01 16:18

Since day one of learning Java I\'ve been told by various websites and many teachers that arrays are consecutive memory locations which can store the specified number of data al

9条回答
  •  一整个雨季
    2021-02-01 17:04

    Your two diagrams are, apart from labels that are strictly for human consumption, equivalent and identical.

    That is to say that in the first diagram, the labels arr[0], arr[1], etc., are not part of the array. They are simply there for illustrative purposes, indicating how the array elements are laid out in memory.

    What you were told, namely that arrays are stored in contiguous locations in memory (at least insofar as virtual addresses are concerned; on modern hardware architectures, these need not map into contiguous physical addresses) and array elements are located based on their size and index, is correct. (At least in... well, it is definitely correct in C/C++. It is almost certainly correct in most, if not all, Java implementations. But it is likely incorrect in languages that allow for sparse arrays or arrays that can grow or shrink dynamically.)

    The fact that the array reference is created in the stack whereas the array data are placed on the heap is an implementation-specific detail. Compilers that compile Java directly to machine code may implement array storage differently, taking into account the specific characteristics of the target hardware platform. In fact, a clever compiler may place, e.g., small arrays in the stack in their entirety, and use the heap only for larger arrays, to minimize the need for garbage collection, which can impact performance.

提交回复
热议问题