Java 用于迭代ArrayList
在本文中,我们将了解如何迭代ArrayList。ArrayList类是一个可调整大小的数组,可以在java.util包中找到。在Java中,内置数组和ArrayList之间的区别在于数组的大小是不能被修改的。
下面是相同的示例−
假设我们的输入是 −
Run the program
所期望的输出将是 −
A elements of the list are:
50 100 150 200 250 300 350
步骤
Step 1 - START
Step 2 - Declare namely
Step 3 - Define the values.
Step 4 - Create a list of integers and initialize elements in it.
Step 5 - Display the list on the console.
Step 6 - Iterate over the elements, and fetch each element using ‘get’ method.
Step 7 - Display this on the console.
Step 6 - Stop
示例1
在这里,我们将所有操作绑定在“main”函数下面。
import java.util.*;
public class Demo {
public static void main(String[] args){
System.out.println("The required packages have been imported");
List<Integer> numbers = Arrays.asList(50, 100, 150, 200, 250, 300, 350);
System.out.println("A list is declared");
System.out.println("\nA elements of the list are: ");
for (int i = 0; i < numbers.size(); i++)
System.out.print(numbers.get(i) + " ");
}
}
输出
The required packages have been imported
A list is declared
A elements of the list are:
50 100 150 200 250 300 350
示例2
在这里,我们将操作封装到展示面向对象编程的函数中。
import java.util.*;
public class Demo {
static void multiply(List<Integer> numbers){
System.out.println("\nA elements of the list are: ");
for (int i = 0; i < numbers.size(); i++)
System.out.print(numbers.get(i) + " ");
}
public static void main(String[] args){
System.out.println("The required packages have been imported");
List<Integer> input_list = Arrays.asList(50, 100, 150, 200, 250, 300, 350);
System.out.println("A list is declared");
multiply(input_list);
}
}
输出
The required packages have been imported
A list is declared
A elements of the list are:
50 100 150 200 250 300 350