获取集合大小的 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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP