在Java For-each中从集合中检索元素
“for-each”循环用于迭代存储在数据结构中的一组元素。
语法
for (element e: collection) {
System.out.println(e);
}示例
以下是一个例子-
public class Demo {
public static void main(String[] args) {
int[] my_vals = {5, 67, 89, 31, -1, 2, 0};
int sum = 0;
for (int number: my_vals) {
sum += number;
}
System.out.println("The sum is " + sum);
}
}输出结果
The sum is 193
名为Demo的类包含主要函数,该函数定义具有某些值的整数数组。最初将总和定义为0,然后对数组进行迭代,并将数组中的每个元素添加到总和中。最终结果显示在屏幕上。