Java list size()方法及实例

Java list size()方法及实例

Java中List接口的 size() 方法是用来获取这个列表中的元素数量。也就是说,这个方法返回这个列表容器中存在的元素的数量。

语法

public int size()

参数 :此方法不接受任何参数。

返回值 :该方法返回该列表中的 元素数量

Java中的List size方法及实例

说明: 假设它是一个整数列表

Input  : {3,2,1,5,7} 
Output : 5

例1 :

// Java program to Illustrate size() method
// of List class for Integer value
 
// Importing required classes
import java.util.*;
 
// Main class
public class GFG {
 
    // Main driver method
    public static void main(String[] arg)
    {
        // Creating object of ArrayList class
        List<Integer> list = new ArrayList<Integer>();
 
        // Populating List by adding integer elements
        // using add() method
        list.add(1);
        list.add(2);
        list.add(3);
        list.add(4);
        list.add(5);
 
        // Printing elements of List
        System.out.println("Before operation: " + list);
 
        // Getting total size of list
        // using size() method
        int size = list.size();
 
        // Printing the size of List
        System.out.println("Size of list = " + size);
    }
}

输出

Before operation: [1, 2, 3, 4, 5]
Size of list = 5

例2 :

// Java program to Illustrate size() method
// of List class for Integer value
 
// Importing required classes
import java.util.*;
 
// Main class
public class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
        // Creating an empty string list by
        // declaring elements of string type
        List<String> list = new ArrayList<String>();
 
        // Populating List by adding string elements
        // using add() method
        list.add("Geeks");
        list.add("for");
        list.add("Geeks");
 
        // Printing the List
        System.out.println("Before operation: " + list);
 
        // Getting total size of list
        // using size() method
        int size = list.size();
 
        // Printing the size of list
        System.out.println("Size of list = " + size);
    }
}

输出

Before operation: [Geeks, for, Geeks]
Size of list = 3

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程