在Java中,for循环和增强型for循环之间的区别是什么?

2023年 8月 28日 69.6k 0

在Java中,for循环和增强型for循环之间的区别是什么?

当涉及到迭代元素时,Java提供了许多选择,其中两个流行的循环结构是传统的和增强的“for each”循环,它们分别提供了不同的方法来完成这个任务。了解这些机制的差异是Java程序员在特定情况下选择最适合的样式的重要信息。

语法

The syntax of the traditional for loop is as follows:

for (initialization; condition; increment/decrement) {
// Code to be executed
}

登录后复制

增强型for循环,也被称为“foreach”循环,具有不同的语法:

for (datatype variable : collection) {
// Code to be executed
}

登录后复制

语法解释

The conventional for loop consists of three parts: initialization, condition, and increment/decrement. The initialization step is executed as it were once at the starting. The condition is evaluated before each cycle, and on the off chance that it is genuine, the code inside the loop is executed. After each cycle, the increment/decrement step is performed.

On the other hand, the improved for loop simplifies the language structure by eliminating the requirement for initialization, condition, and increment/decrement steps. It directly iterates over a collection or array.

Approach 1: Traditional for loop

Algorithm

  • Initialize a variable.

  • Specify the condition for executing the loop.

  • Execute the code block inside the loop.

  • Increment or decrement the variable.

Example

的中文翻译为:

示例

public class TraditionalForLoopExample {
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
System.out.println("Iteration: " + i);
}
}
}

登录后复制

Output

Iteration: 0
Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4

登录后复制

Explanation

的中文翻译为:

解释

代码以声明一个名为TraditionalForLoopExample的公共类开始

在课堂的范围内,人们可以发现一个被称为主方法的基本过程。这个组件作为程序开始执行的入口。

The for keyword indicates the start of the loop construct.

int i = 0 initializes a loop control variable i with an initial value of 0.

i < 5 is the condition that determines whether the loop should continue executing. As long as i is less than 5, the loop will continue iterating.

This code employs an iteration statement in order to update an incrementing integer variable named 'i'. In each subsequent cycle through our program loop implementation, we add one (via '++', as mentioned) to whatever present value for 'i' we encounter via our command stream here- allowing us to track current iterators with ease. Contained within a block cited via brackets {}, we have everything that comes under our programmatic umbrella when we talk about 'the loop.' Herein lies a special command - System.out.println("Iteration: " + i); - outputting data comprising both text ("Iteration") and variables on-screen at present when run.

循环会继续执行,直到条件 i < 5 变为假。在这种情况下,当 i 达到值为 5 时,条件不再为真,循环终止。

Approach 2: Enhanced for loop

Algorithm

  • 声明一个变量来保存集合中的每个元素。

  • Specify the collection to be iterated.

  • 在循环中执行代码块,使用声明的变量访问每个元素。

  • Consider the following example of the enhanced for loop

Example

的中文翻译为:

示例

public class EnhancedForLoopExample {
public static void main(String[] args) {
String[] fruits = {"Apple", "Banana", "Orange"};
for (String fruit : fruits) {
System.out.println("Fruit: " + fruit);
}
}
}

登录后复制

Output

Fruit: Apple
Fruit: Banana
Fruit: Orange

登录后复制

Explanation

的中文翻译为:

解释

代码以声明一个名为EnhancedForLoopExample的公共类开始。

在课堂的范围内,人们可以发现一个被称为主方法的基本过程。这个组件作为程序开始执行的入口。

声明了一个名为fruits的String类型的数组。这行代码创建了一个名为fruits的数组,可以存储String值。该数组被初始化为三个元素:"Apple","Banana"和"Orange"。

The enhanced for loop simplifies the process of iterating over arrays and collections.

循环遍历水果数组中的每个元素,将当前元素赋值给循环变量fruit。

对于每次迭代,执行用花括号{}括起来的代码块,可以轻松地打印出水果数组中的每个单独元素。输出包括一个静态标签“Fruit:”和一个表示当前迭代过程中任意特定项的变量值,通过System.out.println("Fruit: " + fruit);。这种方法消除了与手动索引技术常用于遍历数组等数据集相关的顺序错位或索引间隙的风险。

Difference Between for loop and Enhanced for loop in Java

差异点

Traditional for Loop

增强型for循环

Syntax

Requires explicit initialization, condition, and increment/decrement steps

简化语法,无需初始化、条件或增减步骤

Iteration Control

提供了更多对初始化、条件和增量/减量步骤的控制

自动迭代集合或数组的元素

访问元素

Can access elements using an index variable and array/collection size

直接访问元素,无需索引或大小

代码可读性

Requires explicit handling of iteration details

通过抽象迭代细节来提高代码可读性

Use Cases

Suitable for situations where explicit control over iteration is necessary

Ideal for iterating over collections or arrays without complex iteration requirements

Conclusion

Both the traditional for loop and the enhanced for loop have their own significance in Java programming. The conventional for loop gives more adaptability and control over the emphasis handle, permitting the software engineer to characterize the initialization, condition, and increment/decrement steps. It is commonly utilized when the number of cycles or the particular conditions are known in development.

以上就是在Java中,for循环和增强型for循环之间的区别是什么?的详细内容,更多请关注每日运维网(www.mryunwei.com)其它相关文章!

相关文章

JavaScript2024新功能:Object.groupBy、正则表达式v标志
PHP trim 函数对多字节字符的使用和限制
新函数 json_validate() 、randomizer 类扩展…20 个PHP 8.3 新特性全面解析
使用HTMX为WordPress增效:如何在不使用复杂框架的情况下增强平台功能
为React 19做准备:WordPress 6.6用户指南
如何删除WordPress中的所有评论

发布评论