Java中的 ArrayList size() 方法及示例
Java.util.ArrayList类的size()方法用于获取此列表中元素的数量。
句法:
public int size()
返回值:此方法返回此列表中的元素数。
以下是说明 size() 方法的示例。
示例 1:
// Java program to demonstrate
// size() method
// for Integer value
import java.util.*;
public class GFG1 {
public static void main(String[] argv)
throws Exception
{
try {
// Creating object of ArrayList
ArrayList
arrlist = new ArrayList();
// Populating arrlist1
arrlist.add(1);
arrlist.add(2);
arrlist.add(3);
arrlist.add(4);
arrlist.add(5);
// print arrlist
System.out.println("Before operation: "
+ arrlist);
// getting total size of arrlist
// using size() method
int size = arrlist.size();
// print the size of arrlist
System.out.println("Size of list = "
+ size);
}
catch (IndexOutOfBoundsException e) {
System.out.println("Exception thrown: "
+ e);
}
}
}
输出:
Before operation: [1, 2, 3, 4, 5]
Size of list = 5
示例 2:
// Java program to demonstrate
// size() method
// for String value
import java.util.*;
public class GFG1 {
public static void main(String[] argv)
throws Exception
{
try {
// Creating object of ArrayList
ArrayList
arrlist = new ArrayList();
// Populating arrlist1
arrlist.add("A");
arrlist.add("B");
arrlist.add("C");
// print arrlist
System.out.println("Before operation: "
+ arrlist);
// getting total size of arrlist
// using size() method
int size = arrlist.size();
// print the size of arrlist
System.out.println("Size of list = "
+ size);
}
catch (IndexOutOfBoundsException e) {
System.out.println("Exception thrown: "
+ e);
}
}
}
输出:
Before operation: [A, B, C]
Size of list = 3