Does an array object explicitly contain the indexes?

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

    The reference of an array is not always on the stack. It could also be stored on the heap if it's a member of a class.

    The array itself can hold either primitive values or references to an object. In any case, the data of an array are always of the same kind. Then the compiler can deal with their location without explicit pointers, only with the value/reference size and an index.

    See:
    * The Java Language Specification, Java SE 8 Edition - Arrays
    * The Java Virtual Machine Specification, Java SE 8 Edition - Reference Types and Values

    0 讨论(0)
  • 2021-02-01 17:09

    In Java, arrays are objects. See the JLS - Chapter 10. Arrays:

    In the Java programming language, arrays are objects (§4.3.1), are dynamically created, and may be assigned to variables of type Object (§4.3.2). All methods of class Object may be invoked on an array.

    If you look at 10.7. Array Members chapter, you'll see that the index is not part of the array member:

    The members of an array type are all of the following:

    The public final field length, which contains the number of components of the array. length may be positive or zero.

    • The public method clone, which overrides the method of the same name in class Object and throws no checked exceptions. The return type of the clone method of an array type T[] is T[].

    • All the members inherited from class Object; the only method of Object that is not inherited is its clone method.

    Since the size of each type is known, you can easily determine the location of each component of the array, given the first one.

    The complexity of accessing an element is O(1) since it only needs to calculate the address offset. It's worth mentioning that this behavior is not assumed for all programming languages.

    0 讨论(0)
  • 2021-02-01 17:10

    An array is a contigious memory allocation, which means if you know the address of the first element you can go to the next index by stepping to next memory address.

    The reference array is not the array address, but the way to reach the address (done internally) like normal objects. So you can say you have the position from where the array starts, and you can move a memory address by changing the indexes. So this is why indexes are not specified in the memory; the compiler just knows where to go.

    0 讨论(0)
提交回复
热议问题