获得元素个数是在做循环是必要的操作。
在Array中是采用它实例属性来计数的,即
int[] a=new int[]{2,3,4,5,6};
for(int i=0;i<a.length;i++)
{
System.out.println(a[i]);
}
而对于String和Collection 而言它们提供了一个方法来获取。
String str=new String("hello");
System.out.println(“字符串的长度:”+str.length());
//
//Collection使用实例方法size()获取集合长度
Collection box=new ArrayList();
box.add("hello");
box.add("world");
System.out.println("集合中的元素个数是:"+box.size());