Maison  >  Article  >  Java  >  Quelle est la différence entre la boucle for et la boucle for améliorée en Java ?

Quelle est la différence entre la boucle for et la boucle for améliorée en Java ?

王林
王林avant
2023-08-19 19:45:261410parcourir

Quelle est la différence entre la boucle for et la boucle for améliorée en Java ?

当涉及到迭代元素时,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

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

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

Nécessite des étapes explicites d'initialisation, de condition et d'incrémentation/décrémentation

Syntaxe simplifiée, aucune initialisation, conditions ou étapes d'addition ou de soustraction requises

Contrôle des itérations

Fournit plus de contrôle sur l'initialisation, les conditions et les étapes d'incrémentation/décrémentation

Itérer automatiquement les éléments d'une collection ou d'un tableau

Accès aux éléments

Peut accéder aux éléments à l'aide d'une variable d'index et d'une taille de tableau/collection

Accès direct aux éléments, aucune indexation ni taille requise

Lisibilité du code

Nécessite une gestion explicite des détails de l'itération

Améliorer la lisibilité du code en faisant abstraction des détails de l'itération

Cas d'utilisation

Convient aux situations où un contrôle explicite sur l'itération est nécessaire

Idéal pour parcourir des collections ou des tableaux sans exigences d'itération complexes

Conclusion

La boucle for traditionnelle et la boucle for améliorée ont leur propre signification dans la programmation Java. La boucle for conventionnelle offre plus d'adaptabilité et de contrôle sur la poignée d'accentuation, permettant à l'ingénieur logiciel de caractériser les étapes d'initialisation, de condition et d'incrémentation/décrémentation. Il est couramment utilisé lorsque le nombre de cycles ou les conditions particulières du développement sont connus.

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration:
Cet article est reproduit dans:. en cas de violation, veuillez contacter admin@php.cn Supprimer