獲取集合大小的 Java 程式


在本文中,我們將瞭解如何獲取集合的大小。集合是一個框架,它提供一種架構來儲存和操作物件組。Java 集合可以實現你對資料執行的所有操作,例如搜尋、排序、插入、操作和刪除。

以下是相同內容的演示 −

假設我們的輸入是

Input list: [100, 180, 250, 300]

所需的輸出應該是

The size of the list = 4

演算法

Step 1 - START
Step 2 - Declare a list namely input_list.
Step 3 - Define the values.
Step 4 - Using the function size(), we get the size of the input_list.
Step 5 - Display the result
Step 6 - Stop

示例 1

在這裡,我們將所有操作繫結在一起,置於“main”函式下。

import java.util.*;
public class Demo {
   public static void main(String[] args){
      List<Integer> input_list = new ArrayList<Integer>();
      input_list.add(100);
      input_list.add(180);
      input_list.add(250);
      input_list.add(300);
      System.out.println("The list is defined as: " + input_list);
      int list_size = input_list.size();
      System.out.println("\nThe size of the list = " + list_size);
   }
}

輸出

The list is defined as: [100, 180, 250, 300]

The size of the list = 4

示例 2

在這裡,我們將操作封裝到函式中,展現面向物件程式設計。

import java.util.*;
public class Demo {
   static void print_size(List<Integer> input_list){
      int list_size = input_list.size();
      System.out.println("\nThe size of the list = " + list_size);
   }
   public static void main(String[] args){
      List<Integer> input_list = new ArrayList<Integer>();
      input_list.add(100);
      input_list.add(180);
      input_list.add(250);
      input_list.add(300);
      System.out.println("The list is defined as: " + input_list);
      print_size(input_list);
   }
}

輸出

The list is defined as: [100, 180, 250, 300]

The size of the list = 4

更新日期:2022 年 3 月 30 日

129 次瀏覽

開啟您的 職業生涯

完成課程獲取認證

開始學習
廣告