Un tableau multidimensionnel . Les tableaux multidimensionnels les plus couramment utilisés sont les tableaux 2D et 3D. Nous pouvons dire que tout tableau de dimension supérieure est essentiellement un tableau de tableaux. Un exemple très courant de tableau 2D est l’échiquier. Un échiquier est une grille contenant 64 cases carrées 1×1. Vous pouvez de la même manière visualiser un tableau 2D. Dans un tableau 2D, chaque élément est associé à un numéro de ligne et un numéro de colonne. L'accès à n'importe quel élément du tableau 2D est similaire à l'accès à l'enregistrement d'un fichier Excel en utilisant à la fois le numéro de ligne et le numéro de colonne. Les tableaux 2D sont utiles lors de la mise en œuvre d'un jeu de Tic-Tac-Toe, d'échecs ou même du stockage des pixels de l'image.

Déclaration d'un tableau 2D en Java :
Tout tableau à 2 dimensions peut être déclaré comme suit :
Syntaxe:
data_type nom_tableau[][]; (OU) data_type[][] array_name ;
- data_type : Puisque Java est un langage à typage statique (c'est-à-dire qu'il s'attend à ce que ses variables soient déclarées avant de pouvoir se voir attribuer des valeurs). Ainsi, spécifier le type de données décide du type d’éléments qu’il acceptera. par exemple. pour stocker uniquement des valeurs entières, le type de données sera déclaré comme int. array_name : C'est le nom donné au tableau 2D. par exemple. matières, étudiants, fruits, département, etc.
Note: Nous pouvons écrire [ ][ ] après data_type ou nous pouvons écrire [ ][ ] après array_name lors de la déclaration du tableau 2D.
Java
chaîne en entier en java
// java program showing declaration of arrays> import> java.io.*;> > class> GFG {> >public> static> void> main(String[] args)> >{> > >int>[][] integer2DArray;>// 2D integer array> >String[][] string2DArray;>// 2D String array> >double>[][] double2DArray;>// 2D double array> >boolean>[][] boolean2DArray;>// 2D boolean array> >float>[][] float2DArray;>// 2D float array> >double>[][] double2DArray;>// 2D double array> >}> }> |
>
>
Différentes approches pour l'initialisation d'un tableau 2D en Java :
type_données[][] array_Name = nouveau data_type[no_of_rows][no_of_columns];
Le nombre total d'éléments dans n'importe quel tableau 2D sera égal à (no_of_rows) * (no_of_columns).
- no_of_rows : le nombre de lignes dans un tableau. par exemple. no_of_rows = 3, alors le tableau aura trois lignes. no_of_columns : Le nombre de colonnes dans un tableau. par exemple. no_of_columns = 4, alors le tableau aura quatre colonnes.
La syntaxe ci-dessus d'initialisation du tableau attribuera des valeurs par défaut à tous les éléments du tableau en fonction du type de données spécifié.
Vous trouverez ci-dessous la mise en œuvre de différentes approches pour initialiser des tableaux 2D :
Approche 1 :
Java
// java program to initialize a 2D array> import> java.io.*;> > class> GFG {> >public> static> void> main(String[] args)> >{> >// Declaration along with initialization> >// 2D integer array with 5 rows and 3 columns> >// integer array elements are initialized with 0> >int>[][] integer2DArray =>new> int>[>5>][>3>];> >System.out.println(> >'Default value of int array element: '> >+ integer2DArray[>0>][>0>]);> > >// 2D String array with 4 rows and 4 columns> >// String array elements are initialized with null> >String[][] string2DArray =>new> String[>4>][>4>];> >System.out.println(> >'Default value of String array element: '> >+ string2DArray[>0>][>0>]);> > >// 2D boolean array with 3 rows and 5 columns> >// boolean array elements are initialized with false> >boolean>[][] boolean2DArray =>new> boolean>[>4>][>4>];> >System.out.println(> >'Default value of boolean array element: '> >+ boolean2DArray[>0>][>0>]);> > >// 2D char array with 10 rows and 10 columns> >// char array elements are initialized with> >// 'u0000'(null character)> >char>[][] char2DArray =>new> char>[>10>][>10>];> >System.out.println(> >'Default value of char array element: '> >+ char2DArray[>0>][>0>]);> > >// First declaration and then initialization> >int>[][] arr;>// declaration> > >// System.out.println('arr[0][0]: '+ arr[0][0]);> >// The above line will throw an error, as we have> >// only declared the 2D array, but not initialized> >// it.> >arr =>new> int>[>5>][>3>];>// initialization> >System.out.println(>'arr[0][0]: '> + arr[>0>][>0>]);> >}> }> |
>
>
Note: Lorsque vous initialisez un tableau 2D, vous devez toujours spécifier la première dimension (nombre de lignes), mais la deuxième dimension (nombre de colonnes) peut être omise.
Dans l'extrait de code ci-dessous, nous n'avons pas précisé le nombre de colonnes. Cependant, le compilateur Java est suffisamment intelligent pour manipuler la taille en vérifiant le nombre d'éléments à l'intérieur des colonnes.
Java
tableau de chaînes c
import> java.io.*;> > class> GFG {> >public> static> void> main(String[] args)> >{> >// The line below will throw an error, as the first> >// dimension(no. of rows) is not specified> >int>[][] arr =>new> int>[][>3>];> > >// The line below will execute without any error, as> >// the first dimension(no. of rows) is specified> >int>[][] arr =>new> int>[>2>][];> >}> }> |
>
>
Vous pouvez accéder à n'importe quel élément d'un tableau 2D à l'aide des numéros de ligne et des numéros de colonne.

Approche 2 :
Dans l'extrait de code ci-dessous, nous n'avons pas précisé le nombre de lignes et de colonnes. Cependant, le compilateur Java est suffisamment intelligent pour manipuler la taille en vérifiant le nombre d'éléments à l'intérieur des lignes et des colonnes.
Java
import> java.io.*;> > class> GFG {> >public> static> void> main(String[] args)> >{> >String[][] subjects = {> >{>'Data Structures & Algorithms'>,> >'Programming & Logic'>,>'Software Engineering'>,> >'Theory of Computation'> },>// row 1> > >{>'Thermodynamics'>,>'Metallurgy'>,> >'Machine Drawing'>,> >'Fluid Mechanics'> },>// row2> > >{>'Signals and Systems'>,>'Digital Electronics'>,> >'Power Electronics'> }>// row3> >};> > >System.out.println(> >'Fundamental Subject in Computer Engineering: '> >+ subjects[>0>][>0>]);> >System.out.println(> >'Fundamental Subject in Mechanical Engineering: '> >+ subjects[>1>][>3>]);> >System.out.println(> >'Fundamental Subject in Electronics Engineering: '> >+ subjects[>2>][>1>]);> >}> }> |
>
>Sortir
Fundamental Subject in Computer Engineering: Data Structures & Algorithms Fundamental Subject in Mechanical Engineering: Fluid Mechanics Fundamental Subject in Electronics Engineering: Digital Electronics>
Approche 3 :
De plus, nous pouvons initialiser chaque élément du tableau séparément. Regardez l'extrait de code ci-dessous :
Java
import> java.io.*;> import> java.util.*;> > class> GFG {> >public> static> void> main(String[] args)> >{> >int>[][] scores =>new> int>[>2>][>2>];> >// Initializing array element at position[0][0],> >// i.e. 0th row and 0th column> >scores[>0>][>0>] =>15>;> >// Initializing array element at position[0][1],> >// i.e. 0th row and 1st column> >scores[>0>][>1>] =>23>;> >// Initializing array element at position[1][0],> >// i.e. 1st row and 0th column> >scores[>1>][>0>] =>30>;> >// Initializing array element at position[1][1],> >// i.e. 1st row and 1st column> >scores[>1>][>1>] =>21>;> > >// printing the array elements individually> >System.out.println(>'scores[0][0] = '> >+ scores[>0>][>0>]);> >System.out.println(>'scores[0][1] = '> >+ scores[>0>][>1>]);> >System.out.println(>'scores[1][0] = '> >+ scores[>1>][>0>]);> >System.out.println(>'scores[1][1] = '> >+ scores[>1>][>1>]);> >// printing 2D array using Arrays.deepToString() method> >System.out.println(> >'Printing 2D array using Arrays.deepToString() method: '>);> >System.out.println(Arrays.deepToString(scores));> >}> }> |
>
>Sortir
scores[0][0] = 15 scores[0][1] = 23 scores[1][0] = 30 scores[1][1] = 21 Printing 2D array using Arrays.deepToString() method: [[15, 23], [30, 21]]>
Approche 4
Utiliser l’approche ci-dessus pour l’initialisation du tableau serait une tâche fastidieuse si la taille du tableau 2D est trop grande. Le moyen efficace consiste à utiliser la boucle for pour initialiser les éléments du tableau dans le cas d'un grand tableau 2D.
Java
import> java.io.*;> > class> GFG {> >public> static> void> main(String[] args)> >{> >int> rows =>80>, columns =>5>;> >int>[][] marks =>new> int>[rows][columns];> > >// initializing the array elements using for loop> >for> (>int> i =>0>; i for (int j = 0; j marks[i][j] = i + j; } } // printing the first three rows of marks array System.out.println('First three rows are: '); for (int i = 0; i <3; i++) { for (int j = 0; j System.out.printf(marks[i][j] + ' '); } System.out.println(); } } }> |
>
>Sortir
First three rows are: 0 1 2 3 4 1 2 3 4 5 2 3 4 5 6>
Note: Nous pouvons utiliser arr. fonction length pour trouver la taille des lignes (1ère dimension), et fonction arr[0].length pour trouver la taille des colonnes (2ème dimension).
Approche 5 : (Tableaux irréguliers)
Il peut y avoir un certain scénario dans lequel vous souhaitez que chaque ligne ait un nombre différent de colonnes. Ce type de tableau est appelé Jagged Array.
Java
import> java.io.*;> > class> GFG {> >public> static> void> main(String[] args)> >{> >// declaring a 2D array with 2 rows> >int> jagged[][] =>new> int>[>2>][];> > >// not specifying the 2nd dimension,> >// and making it as jagged array> >// first row has 2 columns> >jagged[>0>] =>new> int>[>2>];> >// second row has 4 columns> >jagged[>1>] =>new> int>[>4>];> >// Initializing the array> >int> count =>0>;> >for> (>int> i =>0>; i // remember to use jagged[i].length instead of // jagged[0].length, since every row has // different number of columns for (int j = 0; j jagged[i][j] = count++; } } // printing the values of 2D Jagged array System.out.println('The values of 2D jagged array'); for (int i = 0; i for (int j = 0; j System.out.printf(jagged[i][j] + ' '); System.out.println(); } } }> |
>
>Sortir
The values of 2D jagged array 0 1 2 3 4 5>
Programme pour ajouter deux tableaux 2D :
Java
comment ouvrir un fichier avec java
import> java.io.*;> import> java.util.*;> > class> GFG {> >public> static> void> main(String[] args)> >{> >int>[][] arr1 = { {>1>,>2>,>3> }, {>4>,>5>,>6> } };> >int>[][] arr2 = { {>4>,>5>,>6> }, {>1>,>3>,>2> } };> >int>[][] sum =>new> int>[>2>][>3>];> > >// adding two 2D arrays element-wise> >for> (>int> i =>0>; i for (int j = 0; j 0].length; j++) { sum[i][j] = arr1[i][j] + arr2[i][j]; } } System.out.println('Resultant 2D array: '); for (int i = 0; i System.out.println(Arrays.toString(sum[i])); } } }> |
>
>Sortir
Resultant 2D array: [5, 7, 9] [5, 8, 8]>