In Java, why are arrays objects? Are there any specific reasons?

前端 未结 6 2193
半阙折子戏
半阙折子戏 2020-12-17 23:37

Is there any reason why an array in Java is an object?

相关标签:
6条回答
  • 2020-12-18 00:26

    Probably because they wanted to get as close as possible to making everything an object. Native types are there for backward compatibility.

    0 讨论(0)
  • 2020-12-18 00:27

    I'm not sure about the official reason.

    However, it makes sense to me that they are objects because operations can be performed on them (such as taking the length) and it made more sense to support these operations as member functions rather than introduce new keywords. Other operations include clone(), the inherited operations of object, etc. Arrays are also hashable and potentially comparable.

    This is different from C (and native arrays in C++), where your arrays are essentially pointers to a memory offset.

    0 讨论(0)
  • 2020-12-18 00:30

    Having arrays be objects means that you can do operations with them (e.g., someArray.count('foo')) instead of just doing it against them (e.g., count(someArray, 'foo')), which leads to more natural syntax.

    0 讨论(0)
  • 2020-12-18 00:33

    Because the Java Language Specification says so :)

    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.

    So, unlike C++, Java provides true arrays as first-class objects:

    • There is a length member.
    • There is a clone() method which overrides the method of the same name in class Object.
    • Plus all the members of the class Object.
    • An exception is thrown if you attempt to access an array out of bounds.
    • Arrays are instanciated in dynamic memory.
    0 讨论(0)
  • 2020-12-18 00:33

    Another point is that objects are mutable and are passed by reference. In arrays there aren't any fields/methods that you can use to change "properties" of the array, but you sure can mutate the element values. And the benefits of passing arrays by reference are pretty obvious (though functional programmers probably wish Java had immutable lists passed by value).

    Edit: forgot to mention. In the period before autoboxing, it was helpful to be able to store arrays in collections, write them to ObjectStreams etc.

    0 讨论(0)
  • 2020-12-18 00:33

    So that they get all the benefits thereof:

    • getHashCode()
    • toString()

    etc.

    And arrays aren't 'primitive', so if they can't be primitive, they must be objects.

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