Le ensemble() méthode de java.util.ArrayLis t La classe est utilisée pour remplacer l'élément à la position spécifiée dans cette liste par l'élément spécifié.
Syntaxe:
public E set(int index, E element)>
Paramètres: Cette méthode prend l'argument suivant comme paramètre.
- index- index de l'élément à remplacer element- élément à stocker à la position spécifiée
Valeur renvoyée : Cette méthode renvoie le élément précédemment à la position spécifiée.
Exception: Cette méthode jette IndexOutOfBoundsException si l'index n'est pas dans la plage de tailles de ArrayList.
Vous trouverez ci-dessous des exemples pour illustrer ensemble() méthode.
Exemple 1:
carte d'itération Java
dérivé partiel du latex
// 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);> >}> >}> }> |
>
itérer une carte en Java
>Sortir:
Before operation : [1, 2, 3, 4, 5] After operation : [1, 2, 3, 30, 5] Replaced element : 4>
Exemple 2 : Pour 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);> >}> >}> }> |
opérateur ternaire java
>
>Sortir:
Before operation : [1, 2, 3, 4, 5] Trying to Replace the element at (index>Capacité) Exception levée : java.lang.IndexOutOfBoundsException : Index : 7, Taille : 5>