Does an array object explicitly contain the indexes?

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

提交回复
热议问题