Version sans JavaScript, en lecture seule : les ateliers, les quiz et l’exécution du code n’y sont pas. Version complète · Catalogue · Se connecter

Support de cours · chapitre 9

Tableaux

Déclaration, length, indices et tableaux de tableaux.

9.1 Définition

Un tableau est introduit par la syntaxe [], placée à la suite du type des éléments. La taille s’obtient avec l’attribut length.

int[] monTableau = { 10, 20, 30, 40, 50, 60, 70, 80, 90, 100 };
int taille = monTableau.length;
int premierElement = monTableau[0];

// Syntaxe avancee
int[] tb;
int[] tb2 = new int[10];
int[] tb3 = new int[5], tb4 = new int[10];
String[] strValues = new String[5];
String[] noms = { "toto", "titi", "tata" };

Parcours et débordement

public class Demo {
    public static void main(String[] args) {
        int[] notes = { 12, 15, 8, 19 };
        System.out.println("taille : " + notes.length);

        for (int i = 0; i < notes.length; i++) {
            System.out.println("notes[" + i + "] = " + notes[i]);
        }

        // Boucle for-each : quand l'indice ne sert pas
        int somme = 0;
        for (int note : notes) {
            somme += note;
        }
        System.out.println("somme : " + somme);

        // Decommentez pour voir l'exception :
        // System.out.println(notes[4]);
    }
}

9.2 Tableaux à plusieurs dimensions

Un tableau peut avoir plusieurs dimensions : du point de vue de Java, c’est un tableau de tableaux.

Une matrice 3×5 remplie de 0 à 14

public class Demo {
    public static void main(String[] args) {
        int[][] matrice = new int[3][5];

        int k = 0;
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 5; j++) {
                matrice[i][j] = k++;
            }
        }

        for (int i = 0; i < matrice.length; i++) {
            for (int j = 0; j < matrice[i].length; j++) {
                System.out.print(matrice[i][j] + "\t");
            }
            System.out.println();
        }
    }
}