當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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<Integer> 
            ArrayList<Integer> 
                arrlist = new ArrayList<Integer>(); 
  
            // 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<Integer> 
            ArrayList<String> 
                arrlist = new ArrayList<String>(); 
  
            // 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


相關用法


注:本文由純淨天空篩選整理自RohitPrasad3大神的英文原創作品 ArrayList size() method in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。