简体   繁体   中英

Length in Arrays

Just a simple question, but why is length in an array not encapsulated? Is this just for beginners in programming because I feel like a getLength() method would be easy to implement.

I've an assumption but I cant say that this is the reason why the designers of java did it that way.

An array is a container (and an Object of course) with a fixed length. And its a very basic one, so encapsulation in this case would be nice but not critical. Take a look at ArrayList for example, which can be considered as an encapsulation of an array.

A basic array has many benefits over other types that encapsulates it. And so maybe when the first version of Java came out it lacked most of the optimization that it has today. So having a data structure with the simplicity (in term of performance) of an array is a good thing.

Also it could be as simple as they didnt think about that at that time and afterwards they had to maintain a backwards compatibility :)

Anyway, if you find interesting stuff about that (maybe you could email sun/oracle) please post! Thats a nice question.

Although arrays might be interpreted as objects, they're really just a fixed set of memory addresses containing some other object or variable. In this manner, they have attributes, such as .length , but not necessarily methods, like .getLength()

A lot of information about arrays can be found here: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html

That would be easy to implement, and that's why it isn't implemented.

Arrays are simply blocks of storage, with no real controls. They enable an easy and fast storage method for when advanced controls are not required.

You can use things like lists, queues, linked lists, double linked lists etc. which can keep a record of their size, if this is required. Obviously, depending on the language you are using, you may well have to create these yourself.

If you want to have length of array and still use a simple array, you can add 1 to a count variable every time you add something to it and minus one each time you remove something. This will perform the same function as a getLength() method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM