Exemples Java - Utilisation des boucles for et foreach
L'instruction for est relativement simple et sert à parcourir des données en boucle.
Le nombre d'exécutions de la boucle for est déterminé avant l'exécution. La syntaxe est la suivante :
for(初始化; 布尔表达式; 更新) {
//代码语句
}
L'instruction foreach est l'une des nouvelles fonctionnalités de Java 5. Elle offre une grande commodité aux développeurs pour le parcours des tableaux et des collections.
La syntaxe de foreach est la suivante :
for(元素类型t 元素变量x : 遍历对象obj){
引用了x的java语句;
}
L'exemple suivant montre l'utilisation des boucles for et foreach :
Fichier Main.java
public class Main {
public static void main(String[] args) {
int[] intary = { 1,2,3,4};
forDisplay(intary);
foreachDisplay(intary);
}
public static void forDisplay(int[] a){
System.out.println("Utilisation d'une boucle for pour parcourir un tableau");
for (int i = 0; i < a.length; i++) {
System.out.print(a[i] + " ");
}
System.out.println();
}
public static void foreachDisplay(int[] data){
System.out.println("Utilisation d'une boucle foreach pour parcourir un tableau");
for (int a : data) {
System.out.print(a+ " ");
}
}
}
La sortie du code ci-dessus est :
使用 for 循环数组 1 2 3 4 使用 foreach 循环数组 1 2 3 4
Fichier Main.java
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class Main
{
public static void main(String[] args)
{
int[] arr = {1, 2, 3, 4, 5};
System.out.println("----------Utilisation d'une boucle for------------");
for(int i=0; i<arr.length; i++)
{
System.out.println(arr[i]);
}
System.out.println("---------Utilisation de la boucle For-Each-------------");
//Boucle for améliorée For-Each
for(int element:arr)
{
System.out.println(element);
}
System.out.println("---------Boucle For-Each sur un tableau à deux dimensions-------------");
//Parcours d'un tableau à deux dimensions
int[][] arr2 = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}} ;
for(int[] row : arr2)
{
for(int element : row)
{
System.out.println(element);
}
}
//Trois façons de parcourir une collection List
List<String> list = new ArrayList<String>();
list.add("Google");
list.add("Example");
list.add("Taobao");
System.out.println("----------Méthode 1 : boucle for ordinaire-----------");
for(int i = 0; i < list.size(); i++)
{
System.out.println(list.get(i));
}
System.out.println("----------Méthode 2 : Utilisation d'un itérateur-----------");
for(Iterator<String> iter = list.iterator(); iter.hasNext();)
{
System.out.println(iter.next());
}
System.out.println("----------Méthode 3 : boucle For-Each-----------");
for(String str: list)
{
System.out.println(str);
}
}
}
La sortie du code ci-dessus est :
----------使用 for 循环------------ 1 2 3 4 5 ---------使用 For-Each 循环------------- 1 2 3 4 5 ---------For-Each 循环二维数组------------- 1 2 3 4 5 6 7 8 9 ----------方式1:普通for循环----------- Google Example Taobao ----------方式2:使用迭代器----------- Google Example Taobao ----------方式3:For-Each 循环----------- Google Example TaobaoAutres extensions
Exemples Java