我需要帮助!我是初学者,但有更有效的方法来计算列表中的对象数并返回总数??
public int size() {
int length = 0;
// For each loop that can enumerate the list and counts the elements.
for( Object o : this ) {
length++;
}
return length;
}
答案 0 :(得分:2)
如果使用数组,可以使用array.length属性获取元素数。如果您使用的是List
,只需调用对象中的方法size()
即可。例如:
int[] arr = {1,2,3};
arr.length; //3
List<Integer> list = Arrays.asList(1,2,3);
list.size(); //3
答案 1 :(得分:0)
jest
上总是有size
方法,但您可以实现自己的方法。检查一下:
arrayList
import java.util.ArrayList;
import java.util.List;
public class ObjectNum
{
public static void main ( String [ ] args )
{
List < String > stringList = new ArrayList < String > ( );
stringList.add ( "FirstElement" );
stringList.add ( "secondLement" );
List < Integer > intList = new ArrayList < Integer > ( );
intList.add ( 1 );
intList.add ( 2 );
intList.add ( 3 );
//Using default methods
System.out.println ( "Default size stringList: " + stringList.size ( ) );
System.out.println ( "Default size intList: " + intList.size ( ) );
System.out.println ( "Custom size stringList: " +countElements ( stringList ) );
System.out.println ( "Custom size intList: " + countElements ( intList ) );
}
public static <E> int countElements ( List < E > list)
{
int size = 0;
for( Object o : list)
{
size++;
}
return size;
}
}