在java中的长度和长度() [英] length and length() in java
问题描述
为什么我们有一个数组作为属性的长度。 array.length
和字符串,我们有一个方法 str.length()
?
Why do we have length of an array as an attribute. array.length
and for String we have a method str.length()
?
刚进来在我心中,是有一些原因是什么?
Just came in my mind, is there some reason?
推荐答案
简化你可以把它看作是数组的特例,而不是普通班(有点像原语,但不是)一个位。字符串和所有的藏品类,因此得到的大小,长度或类似的事情的方法。
A bit simplified you can think of it as arrays being a special case and not ordinary classes (a bit like primitives, but not). String and all the collections are classes, hence the methods to get size, length or similar things.
我想在设计时的原因是表现,如果他们今天创造了它他们可能拿出像数组支持的集合类来代替。
I guess the reason at the time of the design was performance, if they created it today they had probably come up with something like array backed collection classes instead.
如果有人有兴趣,这里是code的一个小片段来说明产生code,两者之间的区别,首先把源代码:
If anyone is interested, here is a small snippet of code to illustrate the difference between the two in generated code, first the source:
public class LengthTest {
public static void main(String[] args) {
int[] array = {12,1,4};
String string = "Hoo";
System.out.println(array.length);
System.out.println(string.length());
}
}
切割方式字节code的不那么重要组成部分,在最后两行以下的类结果运行的javap -c:
Cutting a way the not so important part of the byte code, running javap -c on the class results in the following for the two last lines:
20: getstatic #3; //Field java/lang/System.out:Ljava/io/PrintStream;
23: aload_1
24: arraylength
25: invokevirtual #4; //Method java/io/PrintStream.println:(I)V
28: getstatic #3; //Field java/lang/System.out:Ljava/io/PrintStream;
31: aload_2
32: invokevirtual #5; //Method java/lang/String.length:()I
35: invokevirtual #4; //Method java/io/PrintStream.println:(I)V
在第一种情况下(20-25)在code只是要求JVM对数组的大小(JNI这会已经到GetArrayLength()的调用),而在字符串的情况下(28-35 ),它需要做的方法调用来获取长度。
In the first case (20-25) the code just ask the JVM for the size of the array (in JNI this would have been a call to GetArrayLength()) whereas in the String case (28-35) it needs to do a method call to get the length.
在90年代中期,没有良好的即时编译器之类的东西,它会完全杀死性能只拥有java.util.Vector中(或类似的东西),而不是一门语言结构,它并没有真正像一个类但快速。他们当然可以掩盖的属性作为一个方法调用,并在编译器处理它,但我认为它会一直变得更加令人困惑有某种东西的一种方法,它是不是一个真正的类。
In the mid 90's, without good JITs and stuff, it would have killed performance totally to only have the java.util.Vector (or something similar) and not a language construct which didn't really behave like a class but was fast. They could of course have masked the property as a method call and handled it in the compiler but I think it would have been even more confusing to have a method on something that isn't a real class.
这篇关于在java中的长度和长度()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!