[英]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? 为什么长度 ,当我们谈论阵列和长度()当我们谈论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. 在JLS第10.7节中规定,数组具有公共最终
length
字段。 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. 为了保持一致性,它本来可以被指定为一种方法 - 但它只是不是......同样
String
可以做出一个实现决定,有一个公共的最终length
字段 - 但同样,它不会那样。
There are a few bits of inconsistency which have survived since 1.0 - obviously these things really can't be changed after release... 有一些不一致的东西,自1.0以来幸存下来 - 显然这些东西在发布后真的无法改变......
String
implements CharSequence
and thus length
needs to be a method in this case since interfaces can only specify methods. String
实现CharSequence
,因此在这种情况下length
需要是一个方法,因为接口只能指定方法。
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. 数组不需要实现任何接口,因此在这种情况下,
length
作为公共final字段实现,以避免额外的方法调用开销。
Edit: 编辑:
As Hot Licks pointed out below, CharSequence
didn't exist before Java 1.4. 正如Hot Licks在下面指出的那样,
CharSequence
在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. 尽管CharSequence显然不是这种设计选择背后的原因(因为它不存在),但选择这种设计仍然有意义,因为String可能需要在未来实现新的接口。
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
就好像你创建了一个类,然后说一个公共静态int num,后来在一个方法中告诉num,这个全局等于某个东西
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.