📜  如何在Java中获取集合的大小?

📅  最后修改于: 2022-05-13 01:55:21.350000             🧑  作者: Mango

如何在Java中获取集合的大小?

给定Java中的 Collection ,任务是找到集合的长度或大小。

例子:

Input: Array_List: [1, 2, 3,4]
Output: 4

Input: Linked_List: [geeks, for, geeks]
Output: 3

可以使用size()方法找到不同集合的大小。此方法返回此集合中的元素数。此方法不带任何参数。

下面是实现:

示例 1:

Java
// Java program to demonstrate
// size() method of collection
  
import java.util.*;
  
public class Example1 {
    public static void main(String[] args)
    {
  
        // Creating object of List
        List Array_List = new ArrayList();
  
        // add elements 
        Array_List.add(1);
        Array_List.add(2);
        Array_List.add(3);
        Array_List.add(3);
  
        // getting total size of list
        // using size() method
        int size = Array_List.size();
  
        // print the size of list
        System.out.println("Size of list = " + size);
  
        // print list
        System.out.println("Array_List = " + Array_List);
    }
}


Java
// Java program to demonstrate
// size() method of Collection
import java.util.*;
import java.io.*;
  
class Example2 {
    public static void main(String[] args)
    {
  
        // Creating object of LinkedList
        LinkedList al = new LinkedList();
  
        // Populating LinkedList
        al.add("GEEKS");
        al.add("FOR");
        al.add("GEEKS");
  
        // getting total size of Linkedlist
        // using size() method
        int size = al.size();
  
        // print the size
        System.out.println("Size of the linkedlist = "
                           + size);
  
        // print Linkedlist
        System.out.println("Linkedlist = " + al);
    }
}


输出
Size of list = 4
Array_List = [1, 2, 3, 3]

示例 2:

Java

// Java program to demonstrate
// size() method of Collection
import java.util.*;
import java.io.*;
  
class Example2 {
    public static void main(String[] args)
    {
  
        // Creating object of LinkedList
        LinkedList al = new LinkedList();
  
        // Populating LinkedList
        al.add("GEEKS");
        al.add("FOR");
        al.add("GEEKS");
  
        // getting total size of Linkedlist
        // using size() method
        int size = al.size();
  
        // print the size
        System.out.println("Size of the linkedlist = "
                           + size);
  
        // print Linkedlist
        System.out.println("Linkedlist = " + al);
    }
}
输出
Size of the linkedlist = 3
Linkedlist = [GEEKS, FOR, GEEKS]