我是靠谱客的博主 迷路毛衣,最近开发中收集的这篇文章主要介绍Java中的for-each(增强的for循环),觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

Java for-each(增强)循环 (Java for-each (Enhanced for) loop)

for loop is used to execute a block of statements, multiple times if the user knows exactly how many iterations are needed or required.

for循环用于执行语句块,如果用户确切知道需要或需要多少次迭代,则使用多次。

Java supports an enhanced version of for loop which is also called for-each loop or enhanced for loop. This loop works on collections (iterable). It iterates over each element of the sequence on by one and executes them.

Java支持for循环增强版本,也称为for-each循环增强的for循环 。 此循环适用于集合(可迭代)。 依次迭代序列的每个元素并执行它们。

Note: Unlike for loop, you cannot alter the content of the sequence inside the for-each loop.

注意:for循环不同,您不能在for-each循环内更改序列的内容。

Syntax of for-each (enhanced for) loop:

for-each(增强的)循环的语法:


for (data_type variable : collection){
//body of the loop;
}

It stores each item of the collection in variable and then executes it.

它将集合的每个项目存储在变量中,然后执行它。

Note: data_type should be the same as the data_type of the collection.

注意: data_type应该与集合的data_type相同。

Java代码演示for-each(增强的)循环示例 (Java code to demonstrate example of for-each (enhanced for) loop)

// java program to demonstrate example of
// for-each (enhanced for) loop
//file name: includehelp.java
public class includehelp {
public static void main(String[] args) {
int array[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
System.out.println("Demonstration of for-each loop");
// for-each loop iterating over array
// with the variable x
// if you change the value of x inside
// the body of the loop then original
// value of the array will remain unaffected
for (int i : array)
System.out.println(i);
}
}

Output

输出量

Demonstration of for-each loop
1
2
3
4
5
6
7
8
9

翻译自: https://www.includehelp.com/java/for-each-enhanced-for-loop.aspx

最后

以上就是迷路毛衣为你收集整理的Java中的for-each(增强的for循环)的全部内容,希望文章能够帮你解决Java中的for-each(增强的for循环)所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(59)

评论列表共有 0 条评论

立即
投稿
返回
顶部