Why isn't there a .length () method for arrays in Java?

Possible duplicate:
Java - array length property
String.length () vs Array.length

I am currently in an AP Computer Science class in high school and I came across this in my reading.

From what I understand .length()

this is the method used for strings, but why is .length()

n't the method applied to arrays? I understand that they are different objects, but why hasn't Java made another method to find the length of arrays?

I appreciate any response I get. Thank!

+3


source to share


3 answers


Arrays are defined in the Java Language Specification # 10.7 . In particular:

Array type elements are as follows:

  • The public finite length of the field that contains the number of array components. length can be positive or zero.
  • [...]


I cannot answer why this approach was chosen by the developers of the language.

Interestingly, this was already in the oak specification , which is the ancestor of Java .

+2


source


Since arrays are fixed length, defined at the time they represent the length of the instance, it is a public final field of the class. There is no need to do this with a method, since there is no computation at runtime.

See this Java spec section for details: http://docs.oracle.com/javase/specs/jls/se7/html/jls-10.html#jls-10.7



Now, as far as design goes, the question of why they didn't provide an accessor to get the value is not specified. This may have been done before any other treaty was established, and this is just a legacy. Only the language designers would know the "why" part of their decision to do it this way.

+5


source


I doubt there is a good technical reason for this.

I suspect this is one of those small inconsistencies that weren't discovered early enough to fix them without breaking a ton of code.

0


source







All Articles