IL impostato() metodo di java.util.ArrayLis T class viene utilizzata per sostituire l'elemento nella posizione specificata in questo elenco con l'elemento specificato.
Sintassi:
public E set(int index, E element)>
parametri: Questo metodo accetta il seguente argomento come parametro.
- indice- indice dell'elemento da sostituire elemento- elemento da memorizzare nella posizione specificata
Valore restituito: Questo metodo restituisce il file elemento precedentemente nella posizione specificata.
Eccezione: Questo metodo lancia IndexOutOfBoundsException se l'indice non rientra nell'intervallo di dimensioni di ArrayList.
Di seguito sono riportati gli esempi per illustrare il impostato() metodo.
Esempio 1:
strutture dati Java
// Java program to demonstrate> // set() method> // for Integer value> > import> java.util.*;> > public> class> GFG1 {> >public> static> void> main(String[] argv)>throws> Exception> >{> >try> {> > >// Creating object of ArrayList> >ArrayList> >arrlist =>new> ArrayList();> > >// Populating arrlist1> >arrlist.add(>1>);> >arrlist.add(>2>);> >arrlist.add(>3>);> >arrlist.add(>4>);> >arrlist.add(>5>);> > >// print arrlist> >System.out.println(>'Before operation: '> >+ arrlist);> > >// Replacing element at the index 3 with 30> >// using method set()> >int> i = arrlist.set(>3>,>30>);> > >// Print the modified arrlist> >System.out.println(>'After operation: '> >+ arrlist);> > >// Print the Replaced element> >System.out.println(>'Replaced element: '> >+ i);> >}> > >catch> (IndexOutOfBoundsException e) {> >System.out.println(>'Exception thrown: '> >+ e);> >}> >}> }> |
nome della città negli Stati Uniti
>
ordina un array java
>Produzione:
Before operation : [1, 2, 3, 4, 5] After operation : [1, 2, 3, 30, 5] Replaced element : 4>
Esempio 2: Per IndexOutOfBoundsException
// Java program to demonstrate> // set() method> // for IndexOutOfBoundsException> > import> java.util.*;> > public> class> GFG1 {> >public> static> void> main(String[] argv)>throws> Exception> >{> >try> {> > >// Creating object of ArrayList> >ArrayList> >arrlist =>new> ArrayList();> > >// Populating arrlist1> >arrlist.add(>1>);> >arrlist.add(>2>);> >arrlist.add(>3>);> >arrlist.add(>4>);> >arrlist.add(>5>);> > >// print arrlist> >System.out.println(>'Before operation : '> >+ arrlist);> > >// Replacing element at the index 7 with 30> >// using method set()> >System.out.println(>'
Trying to Replace'> >+>' the element at'> >+>' (index>Capacità) '>);> >int> i = arrlist.set(>7>,>30>);> > >// Print the modified arrlist> >System.out.println(>'After operation: '> >+ arrlist);> > >// Print the Replaced element> >System.out.println(>'Replaced element: '> >+ i);> >}> > >catch> (IndexOutOfBoundsException e) {> >System.out.println(>'Exception thrown : '> + e);> >}> >}> }> |
modelli di programmazione java
>
>Produzione:
Before operation : [1, 2, 3, 4, 5] Trying to Replace the element at (index>Capacità) Eccezione generata: java.lang.IndexOutOfBoundsException: Indice: 7, Dimensione: 5>