如何在 Java 中查找ArrayList
的长度
通过使用ArrayList
size()
ArrayList
类的方法,我们可以很容易地确定ArrayList
的大小。此方法返回ArrayList
的元素数。
public int size()
示例:
package beginnersbook.com;
import java.util.ArrayList;
public class Details
{
public static void main(String [] args)
{
ArrayList<Integer> al=new ArrayList<Integer>();
System.out.println("Initial size: "+al.size());
al.add(1);
al.add(13);
al.add(45);
al.add(44);
al.add(99);
System.out.println("Size after few additions: "+al.size());
al.remove(1);
al.remove(2);
System.out.println("Size after remove operations: "+al.size());
System.out.println("Final ArrayList: ");
for(int num: al){
System.out.println(num);
}
}
}
输出:
Initial size: 0
Size after few additions: 5
Size after remove operations: 3
Final ArrayList:
1
45
99