Topic: length与size的区别是?

  Print this page

1.length与size的区别是? Copy to clipboard
Posted by: fgh520
Posted on: 2006-05-12 14:57

String[] str = new String[];
str.length()与str.size()的区别是什么?

2.Re:length与size的区别是? [Re: fgh520] Copy to clipboard
Posted by: JavaandC
Posted on: 2006-05-12 15:39

length
Returns the length of this string.

String[] str = new String[]; //没有这么定义的。

str.length(); and str.size();有这个方法吗?好像没有吧:)

3.Re:length与size的区别是? [Re: fgh520] Copy to clipboard
Posted by: zcjl
Posted on: 2006-05-12 15:40

其一,String[] str = new String[];的写法是错误,应该是String[] str = new String[0];或者String[] str = new String[] {};的形式

其二,数组对象既没有length()方法,也没有size()方法,只有一个表示数组长度的length属性,所以这里的str.length()和str.size()都不存在,更谈不上区别

下面演示一下List的size()方法和数组的length属性的使用场景:
List strList = new ArrayList();
strList.add("this is str");
System.out.println(strList.size());
for (int i = 0; i < strList.size(); i++) {
String str = (String)strList.get(i);
System.out.println(str);
}
for (Iterator it = strList.iterator(); it.hasNext();) {
String str = (String) it.next();
System.out.println(str);
}

String[] strArray = (String[])strList.toArray(new String[0]);
System.out.println(strArray.length);
for (int i = 0; i < strArray.length; i++) {
String str = strArray[i];
System.out.println(str);
}

4.Re:length与size的区别是? [Re: fgh520] Copy to clipboard
Posted by: fgh520
Posted on: 2006-05-12 18:51

不好意思。写的太慌了,写错了。
不过,我也明白了。谢谢你们啊!~

5.Re:length与size的区别是? [Re: fgh520] Copy to clipboard
Posted by: sunjavaduke
Posted on: 2006-05-12 19:07

P.S.
length
public int length()
Returns the length of this string. The length is equal to the number of 16-bit Unicode characters in the string.

Specified by:
length in interface CharSequence
Returns:
the length of the sequence of characters represented by this object.
数组对象没有size()方法,String对象有length()方法,但是也没有size()方法,size()方法应该是List,ArrayList,Set,HashSet这样的类的对象的方法吧,表示对象有多少元素。
不知道对不对。


   Powered by Jute Powerful Forum® Version Jute 1.5.6 Ent
Copyright © 2002-2021 Cjsdn Team. All Righits Reserved. 闽ICP备05005120号-1
客服电话 18559299278    客服信箱 714923@qq.com    客服QQ 714923