Metodo get(index) ArrayList in Java con esempi
IL Ottenere() metodo di Lista di array in Java viene utilizzato per ottenere l'elemento di un indice specificato all'interno dell'elenco.
Sintassi:
get(index)
Parametro: Indice degli elementi da restituire. È di tipo dati int.
Tipo di reso: L'elemento all'indice specificato nell'elenco fornito.
Eccezione: Genera IndexOutOfBoundsException se l'indice è fuori intervallo (index=size())
Nota: Complessità temporale : ArrayList è una delle implementazioni List create sopra un array. Quindi, get(index) è sempre un'operazione O(1) a tempo costante.
Esempio:
Giava
// 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);> > }> }> |
Produzione
List: [10, 20, 30, 40] the element at index 2 is 30
Esempio 2 : Programma per dimostrare l'errore
Giava
// 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);> > }> }> |
Produzione :
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)