Le Tableaux cours en paquet java.util fait partie du Cadre de collecte Java . Cette classe fournit des méthodes statiques pour créer et accéder dynamiquement Tableaux Java . Il se compose uniquement de méthodes statiques et des méthodes de la classe Object. Les méthodes de cette classe peuvent être utilisées par le nom de la classe lui-même.
La hiérarchie des classes est la suivante :
java.lang.Object ? java.util.Arrays>
Geek, maintenant vous devez vous demander pourquoi avons-nous besoin de la classe Java Arrays alors que nous sommes capables de déclarer, d'initialiser et de calculer des opérations sur des tableaux. La réponse à cette question réside cependant dans les méthodes de cette classe dont nous allons discuter plus en détail, car pratiquement ces fonctions aident les programmeurs à élargir leurs horizons avec des tableaux. Par exemple, il arrive souvent que boucles sont utilisés pour effectuer certaines tâches sur un tableau comme :
- Remplissez un tableau avec une valeur particulière.
- Trier un tableau.
- Rechercher dans un tableau.
- Et beaucoup plus.
Ici, la classe Arrays fournit plusieurs méthodes statiques qui peuvent être utilisées pour effectuer ces tâches directement sans utiliser de boucles, rendant ainsi notre code très court et optimisé.
Syntaxe: Déclaration de classe
public class Arrays extends Object>
Syntaxe: Pour utiliser des tableaux
Arrays.;>
Méthodes dans la classe Java Array
La classe Arrays du package java.util contient plusieurs méthodes statiques qui peuvent être utilisées pour remplir, trier, rechercher, etc. dans des tableaux. Discutons maintenant des méthodes de cette classe qui sont présentées ci-dessous sous forme de tableau comme suit :
| Méthodes | Action effectuée |
|---|---|
| commeListe() | Renvoie une liste de taille fixe soutenue par les tableaux spécifiés |
| recherche binaire() | Recherche l'élément spécifié dans le tableau à l'aide de l'algorithme de recherche binaire |
| recherche binaire (tableau, fromIndex, toIndex, clé, comparateur) | Recherche dans une plage du tableau spécifié l'objet spécifié à l'aide de l'algorithme de recherche binaire |
| comparer (tableau 1, tableau 2) | Compare lexicographiquement deux tableaux passés en paramètres. |
| copyOf (tableau original, nouvelle longueur) | Copie le tableau spécifié, en le tronquant ou en le remplissant avec la valeur par défaut (si nécessaire) afin que la copie ait la longueur spécifiée. |
| copyOfRange (originalArray, fromIndex, endIndex) | Copie la plage spécifiée du tableau spécifié dans un nouveau tableau. |
| deepEquals(Objet[] a1, Objet[] a2) | Renvoie vrai si les deux tableaux spécifiés sont profondément égaux l’un à l’autre. |
| deepHashCode(Objet[] a) | Renvoie un code de hachage basé sur le contenu approfondi des tableaux spécifiés. |
| profondVersChaîne(Objet[] a) | Renvoie une représentation sous forme de chaîne du contenu profond des tableaux spécifiés. |
| est égal à (tableau1, tableau2) | Vérifie si les deux tableaux sont égaux ou non. |
| remplir (tableau original, valeur de remplissage) | Attribue cette valeur de remplissage à chaque index de ces tableaux. |
| hashCode (tableau original) | Renvoie un hashCode entier de cette instance de tableau. |
| incompatibilité (tableau1, tableau2) | Recherche et renvoie l'index du premier élément sans correspondance entre les deux tableaux spécifiés. |
| parallelPrefix (originalArray, fromIndex, endIndex, functionOperator) | Exécute parallelPrefix pour la plage donnée du tableau avec l'opérateur fonctionnel spécifié. |
| parallelPrefix (originalArray, opérateur) | Exécute parallelPrefix pour un tableau complet avec l'opérateur fonctionnel spécifié. |
| parallelSetAll (originalArray, FunctionalGenerator) | Définit tous les éléments de ce tableau en parallèle, en utilisant la fonction de générateur fournie. |
| tri parallèle (tableau original) | Trie le tableau spécifié en utilisant le tri parallèle. |
| setAll (tableau original, générateur fonctionnel) | Définit tous les éléments du tableau spécifié à l'aide de la fonction génératrice fournie. |
| trier (tableau original) | Trie le tableau complet par ordre croissant. |
| trier (originalArray, fromIndex, endIndex) | Trie la plage spécifiée du tableau par ordre croissant. |
| sort(T[] a, int fromIndex, int toIndex, Comparator c) | Trie la plage spécifiée du tableau d'objets spécifié selon l'ordre induit par le comparateur spécifié. |
| trier(T[] a, Comparateur c) | Trie le tableau d'objets spécifié selon l'ordre induit par le comparateur spécifié. |
| séparateur (originalArray) | Renvoie un Spliterator couvrant tous les tableaux spécifiés. |
| spliterator (originalArray, fromIndex, endIndex) | Renvoie un Spliterator du type du tableau couvrant la plage spécifiée des tableaux spécifiés. |
| flux (tableau original) | Renvoie un flux séquentiel avec le tableau spécifié comme source. |
| versChaîne(tableauoriginal) | Il renvoie une représentation sous forme de chaîne du contenu de ce tableau. La représentation sous forme de chaîne consiste en une liste d’éléments du tableau, entourés de crochets ([]). Les éléments adjacents sont séparés par les caractères une virgule suivie d'un espace. Les éléments sont convertis en chaînes comme par la fonction String.valueOf(). |
Mise en œuvre:
Exemple 1: commeListe() Méthode
Java
// Java Program to Demonstrate Arrays Class> // Via asList() method> > // Importing Arrays utility class> // from java.util package> import> java.util.Arrays;> > // Main class> class> GFG {> > >// Main driver method> >public> static> void> main(String[] args)> >{> >// Get the Array> >int> intArr[] = {>10>,>20>,>15>,>22>,>35> };> > >// To convert the elements as List> >System.out.println(>'Integer Array as List: '> >+ Arrays.asList(intArr));> >}> }> |
>
>Sortir
Integer Array as List: [[I@2f4d3709]>
Exemple 2 : recherche binaire() Méthode
Cette méthode recherche l'élément spécifié dans le tableau à l'aide de l'algorithme de recherche binaire.
Java
// Java Program to Demonstrate Arrays Class> // Via binarySearch() method> > // Importing Arrays utility class> // from java.util package> import> java.util.Arrays;> > // Main class> public> class> GFG {> > >// Main driver method> >public> static> void> main(String[] args)> >{> > >// Get the Array> >int> intArr[] = {>10>,>20>,>15>,>22>,>35> };> > >Arrays.sort(intArr);> > >int> intKey =>22>;> > >// Print the key and corresponding index> >System.out.println(> >intKey +>' found at index = '> >+ Arrays.binarySearch(intArr, intKey));> >}> }> |
>
>Sortir
22 found at index = 3>
Exemple 3 : méthode binaireSearch(array, fromIndex, toIndex, key, Comparator)
Cette méthode recherche l'objet spécifié dans une plage du tableau spécifié à l'aide de l'algorithme de recherche binaire.
Java
// Java program to demonstrate> // Arrays.binarySearch() method> > import> java.util.Arrays;> > public> class> Main {> >public> static> void> main(String[] args)> >{> > >// Get the Array> >int> intArr[] = {>10>,>20>,>15>,>22>,>35> };> > >Arrays.sort(intArr);> > >int> intKey =>22>;> > >System.out.println(> >intKey> >+>' found at index = '> >+ Arrays> >.binarySearch(intArr,>1>,>3>, intKey));> >}> }> |
>
>Sortir
22 found at index = -4>
Exemple 4 : méthode compare(array 1, array 2)
Java
// Java program to demonstrate> // Arrays.compare() method> > import> java.util.Arrays;> > public> class> Main {> >public> static> void> main(String[] args)> >{> > >// Get the Array> >int> intArr[] = {>10>,>20>,>15>,>22>,>35> };> > >// Get the second Array> >int> intArr1[] = {>10>,>15>,>22> };> > >// To compare both arrays> >System.out.println(>'Integer Arrays on comparison: '> >+ Arrays.compare(intArr, intArr1));> >}> }> |
>
>Sortir
Integer Arrays on comparison: 1>
Exemple 5 : méthode compareUnsigned(array 1, array 2)
Java
// Java program to demonstrate> // Arrays.compareUnsigned() method> > import> java.util.Arrays;> > public> class> Main {> >public> static> void> main(String[] args)> >{> > >// Get the Arrays> >int> intArr[] = {>10>,>20>,>15>,>22>,>35> };> > >// Get the second Arrays> >int> intArr1[] = {>10>,>15>,>22> };> > >// To compare both arrays> >System.out.println(>'Integer Arrays on comparison: '> >+ Arrays.compareUnsigned(intArr, intArr1));> >}> }> |
>
>Sortir
Integer Arrays on comparison: 1>
Exemple 6 : méthode copyOf(originalArray, newLength)
Java
// Java program to demonstrate> // Arrays.copyOf() method> > import> java.util.Arrays;> > public> class> Main {> >public> static> void> main(String[] args)> >{> > >// Get the Array> >int> intArr[] = {>10>,>20>,>15>,>22>,>35> };> > >// To print the elements in one line> >System.out.println(>'Integer Array: '> >+ Arrays.toString(intArr));> > >System.out.println(>'
New Arrays by copyOf:
'>);> > >System.out.println(>'Integer Array: '> >+ Arrays.toString(> >Arrays.copyOf(intArr,>10>)));> >}> }> |
>
>Sortir
Integer Array: [10, 20, 15, 22, 35] New Arrays by copyOf: Integer Array: [10, 20, 15, 22, 35, 0, 0, 0, 0, 0]>
Exemple 7 : méthode copyOfRange(originalArray, fromIndex, endIndex)
Java
// Java program to demonstrate> // Arrays.copyOfRange() method> > import> java.util.Arrays;> > public> class> Main {> >public> static> void> main(String[] args)> >{> > >// Get the Array> >int> intArr[] = {>10>,>20>,>15>,>22>,>35> };> > >// To print the elements in one line> >System.out.println(>'Integer Array: '> >+ Arrays.toString(intArr));> > >System.out.println(>'
New Arrays by copyOfRange:
'>);> > >// To copy the array into an array of new length> >System.out.println(>'Integer Array: '> >+ Arrays.toString(> >Arrays.copyOfRange(intArr,>1>,>3>)));> >}> }> |
>
>Sortir
Integer Array: [10, 20, 15, 22, 35] New Arrays by copyOfRange: Integer Array: [20, 15]>
Exemple 8 : méthode deepEquals(Object[] a1, Object[] a2)
Java
// Java program to demonstrate> // Arrays.deepEquals() method> > import> java.util.Arrays;> > public> class> Main {> >public> static> void> main(String[] args)> >{> > >// Get the Arrays> >int> intArr[][] = { {>10>,>20>,>15>,>22>,>35> } };> > >// Get the second Arrays> >int> intArr1[][] = { {>10>,>15>,>22> } };> > >// To compare both arrays> >System.out.println(>'Integer Arrays on comparison: '> >+ Arrays.deepEquals(intArr, intArr1));> >}> }> |
>
>Sortir
Integer Arrays on comparison: false>
Exemple 9 : méthode deepHashCode(Object[] a)
Java
// Java program to demonstrate> // Arrays.deepHashCode() method> > import> java.util.Arrays;> > public> class> Main {> >public> static> void> main(String[] args)> >{> > >// Get the Array> >int> intArr[][] = { {>10>,>20>,>15>,>22>,>35> } };> > >// To get the dep hashCode of the arrays> >System.out.println(>'Integer Array: '> >+ Arrays.deepHashCode(intArr));> >}> }> |
>
>Sortir
Integer Array: 38475344>
Exemple 10 : méthode deepToString(Object[] a)
Java
// Java program to demonstrate> // Arrays.deepToString() method> > import> java.util.Arrays;> > public> class> Main {> >public> static> void> main(String[] args)> >{> > >// Get the Array> >int> intArr[][] = { {>10>,>20>,>15>,>22>,>35> } };> > >// To get the deep String of the arrays> >System.out.println(>'Integer Array: '> >+ Arrays.deepToString(intArr));> >}> }> |
>
>Sortir
Integer Array: [[10, 20, 15, 22, 35]]>
Exemple 11 : méthode equals(array1, array2)
Java
menu des paramètres du téléphone Android
// Java program to demonstrate> // Arrays.equals() method> > import> java.util.Arrays;> > public> class> Main {> >public> static> void> main(String[] args)> >{> > >// Get the Arrays> >int> intArr[] = {>10>,>20>,>15>,>22>,>35> };> > >// Get the second Arrays> >int> intArr1[] = {>10>,>15>,>22> };> > >// To compare both arrays> >System.out.println(>'Integer Arrays on comparison: '> >+ Arrays.equals(intArr, intArr1));> >}> }> |
>
>Sortir
Integer Arrays on comparison: false>
Exemple 12 : remplir (tableau original, valeur de remplissage) Méthode
Java
// Java program to demonstrate> // Arrays.fill() method> > import> java.util.Arrays;> > public> class> Main {> >public> static> void> main(String[] args)> >{> > >// Get the Arrays> >int> intArr[] = {>10>,>20>,>15>,>22>,>35> };> > >int> intKey =>22>;> > >Arrays.fill(intArr, intKey);> > >// To fill the arrays> >System.out.println(>'Integer Array on filling: '> >+ Arrays.toString(intArr));> >}> }> |
>
>Sortir
Integer Array on filling: [22, 22, 22, 22, 22]>
Exemple 13 : hashCode(originalArray) Méthode
Java
// Java program to demonstrate> // Arrays.hashCode() method> > import> java.util.Arrays;> > public> class> Main {> >public> static> void> main(String[] args)> >{> > >// Get the Array> >int> intArr[] = {>10>,>20>,>15>,>22>,>35> };> > >// To get the hashCode of the arrays> >System.out.println(>'Integer Array: '> >+ Arrays.hashCode(intArr));> >}> }> |
>
>Sortir
Integer Array: 38475313>
Exemple 14 : méthode mismatch(array1, array2)
Java
// Java program to demonstrate> // Arrays.mismatch() method> > import> java.util.Arrays;> > public> class> Main {> >public> static> void> main(String[] args)> >{> > >// Get the Arrays> >int> intArr[] = {>10>,>20>,>15>,>22>,>35> };> > >// Get the second Arrays> >int> intArr1[] = {>10>,>15>,>22> };> > >// To compare both arrays> >System.out.println(>'The element mismatched at index: '> >+ Arrays.mismatch(intArr, intArr1));> >}> }> |
CSS gras
>
>Sortir
The element mismatched at index: 1>
Exemple 15 : méthode parallelSort(originalArray)
Java
// Java program to demonstrate> // Arrays.parallelSort() method> > // Importing Arrays class from> // java.util package> import> java.util.Arrays;> > // Main class> public> class> Main {> >public> static> void> main(String[] args)> >{> > >// Get the Array> >int> intArr[] = {>10>,>20>,>15>,>22>,>35> };> > >// To sort the array using parallelSort> >Arrays.parallelSort(intArr);> > >System.out.println(>'Integer Array: '> >+ Arrays.toString(intArr));> >}> }> |
>
>Sortir
Integer Array: [10, 15, 20, 22, 35]>
Exemple 16 : trier (tableau original) Méthode
Java
// Java program to demonstrate> // Arrays.sort() method> > import> java.util.Arrays;> > public> class> Main {> >public> static> void> main(String[] args)> >{> > >// Get the Array> >int> intArr[] = {>10>,>20>,>15>,>22>,>35> };> > >// To sort the array using normal sort-> >Arrays.sort(intArr);> > >System.out.println(>'Integer Array: '> >+ Arrays.toString(intArr));> >}> }> |
>
>Sortir
Integer Array: [10, 15, 20, 22, 35]>
Exemple 17 : trier (originalArray, fromIndex, endIndex) Méthode
Java
// Java program to demonstrate> // Arrays.sort() method> > import> java.util.Arrays;> > public> class> Main {> >public> static> void> main(String[] args)> >{> > >// Get the Array> >int> intArr[] = {>10>,>20>,>15>,>22>,>35> };> > >// To sort the array using normal sort> >Arrays.sort(intArr,>1>,>3>);> > >System.out.println(>'Integer Array: '> >+ Arrays.toString(intArr));> >}> }> |
>
>Sortir
Integer Array: [10, 15, 20, 22, 35]>
Exemple 18 : sort(T[] a, int fromIndex, int toIndex, Comparator c) Méthode
Java
// Java program to demonstrate working of Comparator> // interface> import> java.util.*;> import> java.lang.*;> import> java.io.*;> > // A class to represent a student.> class> Student {> >int> rollno;> >String name, address;> > >// Constructor> >public> Student(>int> rollno, String name,> >String address)> >{> >this>.rollno = rollno;> >this>.name = name;> >this>.address = address;> >}> > >// Used to print student details in main()> >public> String toString()> >{> >return> this>.rollno +>' '> >+>this>.name +>' '> >+>this>.address;> >}> }> > class> Sortbyroll>implements> Comparator {> >// Used for sorting in ascending order of> >// roll number> >public> int> compare(Student a, Student b)> >{> >return> a.rollno - b.rollno;> >}> }> > // Driver class> class> Main {> >public> static> void> main(String[] args)> >{> >Student[] arr = {>new> Student(>111>,>'bbbb'>,>'london'>),> >new> Student(>131>,>'aaaa'>,>'nyc'>),> >new> Student(>121>,>'cccc'>,>'jaipur'>) };> > >System.out.println(>'Unsorted'>);> >for> (>int> i =>0>; i System.out.println(arr[i]); Arrays.sort(arr, 1, 2, new Sortbyroll()); System.out.println('
Sorted by rollno'); for (int i = 0; i System.out.println(arr[i]); } }> |
>
>Sortir
Unsorted 111 bbbb london 131 aaaa nyc 121 cccc jaipur Sorted by rollno 111 bbbb london 131 aaaa nyc 121 cccc jaipur>
Exemple 19 : trier(T[] a, Comparateur c) Méthode
Java
// Java program to demonstrate working of Comparator> // interface> import> java.util.*;> import> java.lang.*;> import> java.io.*;> > // A class to represent a student.> class> Student {> >int> rollno;> >String name, address;> > >// Constructor> >public> Student(>int> rollno, String name,> >String address)> >{> >this>.rollno = rollno;> >this>.name = name;> >this>.address = address;> >}> > >// Used to print student details in main()> >public> String toString()> >{> >return> this>.rollno +>' '> >+>this>.name +>' '> >+>this>.address;> >}> }> > class> Sortbyroll>implements> Comparator {> > >// Used for sorting in ascending order of> >// roll number> >public> int> compare(Student a, Student b)> >{> >return> a.rollno - b.rollno;> >}> }> > // Driver class> class> Main {> >public> static> void> main(String[] args)> >{> >Student[] arr = {>new> Student(>111>,>'bbbb'>,>'london'>),> >new> Student(>131>,>'aaaa'>,>'nyc'>),> >new> Student(>121>,>'cccc'>,>'jaipur'>) };> > >System.out.println(>'Unsorted'>);> >for> (>int> i =>0>; i System.out.println(arr[i]); Arrays.sort(arr, new Sortbyroll()); System.out.println('
Sorted by rollno'); for (int i = 0; i System.out.println(arr[i]); } }> |
>
>Sortir
Unsorted 111 bbbb london 131 aaaa nyc 121 cccc jaipur Sorted by rollno 111 bbbb london 121 cccc jaipur 131 aaaa nyc>
Exemple 20 : méthode spliterator(originalArray)
Java
// Java program to demonstrate> // Arrays.spliterator() method> > import> java.util.Arrays;> > public> class> Main {> >public> static> void> main(String[] args)> >{> > >// Get the Array> >int> intArr[] = {>10>,>20>,>15>,>22>,>35> };> > >// To sort the array using normal sort> >System.out.println(>'Integer Array: '> >+ Arrays.spliterator(intArr));> >}> }> |
>
>Sortir
Integer Array: java.util.Spliterators$IntArraySpliterator@4e50df2e>
Exemple 21 : méthode spliterator(originalArray, fromIndex, endIndex)
Java
// Java program to demonstrate> // Arrays.spliterator() method> > import> java.util.Arrays;> > public> class> Main {> >public> static> void> main(String[] args)> >{> > >// Get the Array> >int> intArr[] = {>10>,>20>,>15>,>22>,>35> };> > >// To sort the array using normal sort> >System.out.println(>'Integer Array: '> >+ Arrays.spliterator(intArr,>1>,>3>));> >}> }> |
>
>Sortir
Integer Array: java.util.Spliterators$IntArraySpliterator@4e50df2e>
Exemple 22 : stream(originalArray) Méthode
Java
// Java program to demonstrate> // Arrays.stream() method> > import> java.util.Arrays;> > public> class> Main {> >public> static> void> main(String[] args)> >{> > >// Get the Array> >int> intArr[] = {>10>,>20>,>15>,>22>,>35> };> > >// To get the Stream from the array> >System.out.println(>'Integer Array: '> >+ Arrays.stream(intArr));> >}> }> |
>
>Sortir
Integer Array: java.util.stream.IntPipeline$Head@7291c18f>
Exemple 23 : versChaîne(tableauoriginal) Méthode
Java
// Java program to demonstrate> // Arrays.toString() method> > import> java.util.Arrays;> > public> class> Main {> >public> static> void> main(String[] args)> >{> > >// Get the Array> >int> intArr[] = {>10>,>20>,>15>,>22>,>35> };> > >// To print the elements in one line> >System.out.println(>'Integer Array: '> >+ Arrays.toString(intArr));> >}> }> |
>
>Sortir
Integer Array: [10, 20, 15, 22, 35]>