Does an array object explicitly contain the indexes?

后端 未结 9 2062
时光取名叫无心
时光取名叫无心 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:02

    The array, as you say, will only store objects of the same type. Each type will have a corresponding size, in bytes. For example in an int[] each element will occupy 4 bytes, each byte in a byte[] will occupy 1 byte, each Object in an Object[] will occupy 1 word (because it's really a pointer to the heap), etc.

    The important thing is that each type has a size and every array has a type.

    Then, we get to the problem of mapping an index to a memory position at runtime. It's actually very easy because you know where the array starts and, given the array's type, you know the size of each element.

    If your array starts at some memory position N you can use the the given index I and element size S to compute that the memory you're looking for will be at memory address N + (S * I).

    This is how Java finds memory positions for indexes at runtime without storing them.

提交回复
热议问题