Java中的长度和长度() [英] length and length() in Java
问题描述
为什么我们有一个数组的长度作为属性,array.length
,而对于String,我们有一个方法,str.length()
?>
有什么原因吗?
让我首先强调三种不同的方式来达到类似的目的.
length
-- 数组 (int[]
, double[]
, String[]
) -- 知道数组的长度
length()
-- 字符串相关对象(String
, StringBuilder
, etc) -- 要知道字符串的长度
size()
-- Collection Object (ArrayList
, Set
, etc) -- 要知道集合的大小
现在忘记 length()
只考虑 length
和 size()
.
length
不是一个方法,所以它对对象不起作用是完全合理的.它只适用于数组.size()
它的名字更好地描述了它,因为它是一种方法,它将用于那些使用集合(集合框架)的对象,正如我上面所说的那样.
现在来到length()
:
String 不是原始数组(所以我们不能使用 .length
),也不是集合(所以我们不能使用 .size()
)这就是为什么我们还需要另一个是 length()
(保留差异并达到目的).
作为对为什么?
的回答我觉得它很有用,易于记忆和使用,而且很友好.
Why do we have the length of an array as an attribute, array.length
, and for String we have a method, str.length()
?
Is there some reason?
Let me first highlight three different ways for similar purpose.
length
-- arrays (int[]
, double[]
, String[]
) -- to know the length of the arrays
length()
-- String related Object (String
, StringBuilder
, etc) -- to know the length of the String
size()
-- Collection Object (ArrayList
, Set
, etc) -- to know the size of the Collection
Now forget about length()
consider just length
and size()
.
length
is not a method, so it completely makes sense that it will not work on objects. It only works on arrays.
size()
its name describes it better and as it is a method, it will be used in the case of those objects who work with collection (collection frameworks) as I said up there.
Now come to length()
:
String is not a primitive array (so we can't use .length
) and also not a Collection (so we cant use .size()
) that's why we also need a different one which is length()
(keep the differences and serve the purpose).
As answer to Why?
I find it useful, easy to remember and use and friendly.
这篇关于Java中的长度和长度()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!