Méthode ArrayList get(index) en Java avec exemples
Le obtenir() méthode de Liste des tableaux en Java est utilisé pour obtenir l'élément d'un index spécifié dans la liste.
Syntaxe:
get(index)
Paramètre: Index des éléments à restituer. Il s'agit d'un type de données int.
Type de retour : L'élément à l'index spécifié dans la liste donnée.
Exception: Il lève IndexOutOfBoundsException si l'index est hors plage (index=size())
Note: Complexité temporelle : ArrayList est l'une des implémentations de List construites au sommet d'un tableau. Par conséquent, get(index) est toujours une opération O(1) à temps constant.
Exemple:
Java
// Java Program to Demonstrate the working of> // get() method in ArrayList> > // Importing ArrayList class> import> java.util.ArrayList;> > // Main class> public> class> GFG {> > > // Main driver method> > public> static> void> main(String[] args)> > {> > // Creating an Empty Integer ArrayList> > ArrayList arr => new> ArrayList(> 4> );> > > // Using add() to initialize values> > // [10, 20, 30, 40]> > arr.add(> 10> );> > arr.add(> 20> );> > arr.add(> 30> );> > arr.add(> 40> );> > > // Printing elements of list> > System.out.println(> 'List: '> + arr);> > > // Getting element at index 2> > int> element = arr.get(> 2> );> > > // Displaying element at specified index> > // on console inside list> > System.out.println(> 'the element at index 2 is '> > + element);> > }> }> |
Sortir
List: [10, 20, 30, 40] the element at index 2 is 30
Exemple 2 : Programme pour démontrer l'erreur
Java
// Java Program to Demonstrate Error Generated> // while using get() method in ArrayList> > // Importing ArrayList class> import> java.util.ArrayList;> > // Main class> public> class> GFG {> > > // Main driver method> > public> static> void> main(String[] args)> > {> > // Creating an Empty Integer ArrayList> > ArrayList arr => new> ArrayList(> 4> );> > > // Using add() method to insert elements> > // and adding custom values> > arr.add(> 10> );> > arr.add(> 20> );> > arr.add(> 30> );> > arr.add(> 40> );> > > // Getting element at index 2> > int> element = arr.get(> 5> );> > > // Print all the elements of ArrayList> > System.out.println(> 'the element at index 2 is '> > + element);> > }> }> |
Sortir :
Exception in thread 'main' java.lang.IndexOutOfBoundsException: Index: 5, Size: 4 at java.util.ArrayList.rangeCheck(ArrayList.java:657) at java.util.ArrayList.get(ArrayList.java:433) at GFG.main(GFG.java:22)