简体   繁体   中英

length in arrays and length() in String

Why is length a data field in when we talk about arrays and length() when we talk about String in Java? Means:

int a[10] = {1,2,3,4,5,6,7,8,9,10};
String str = "foo";
int a_len = a.length;
int str_len = str.length();

Why is length not a function in case of arrays or vice versa?

Simply: that's just the way it is, and the way it's always been.

It's specified in JLS section 10.7 that arrays have a public final length field. It could have been specified as a method instead, for consistency - but it just wasn't... equally String could have made an implementation decision to have a public final length field - but again, it happens not to be that way.

There are a few bits of inconsistency which have survived since 1.0 - obviously these things really can't be changed after release...

String implements CharSequence and thus length needs to be a method in this case since interfaces can only specify methods.

Arrays don't need to implement any interface, so length is implemented as a public final field in this case to avoid extra method call overhead.

Edit:

As Hot Licks pointed out below, CharSequence didn't exist before Java 1.4. Although CharSequence obviously wasn't the driving reason behind this design choice (since it didn't exist), it would still make sense to choose this design with the idea that String might need to implement new interfaces in the future.

It's considered a variable and not a method. It would be as if you made a class and said Public static int num and later in a method told that num to be equal to something globally

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