Der Satz() Methode von java.util.ArrayLis T Die Klasse wird verwendet, um das Element an der angegebenen Position in dieser Liste durch das angegebene Element zu ersetzen.
Syntax:
public E set(int index, E element)>
Parameter: Diese Methode verwendet das folgende Argument als Parameter.
- Index – Index des zu ersetzenden Elements. Element – Element, das an der angegebenen Position gespeichert werden soll
Rückgabewert: Diese Methode gibt die zurück Element zuvor an der angegebenen Position.
Ausnahme: Diese Methode wirft IndexOutOfBoundsException wenn der Index nicht im Größenbereich der ArrayList liegt.
Nachfolgend finden Sie Beispiele zur Veranschaulichung Satz() Methode.
Beispiel 1:
Sortierung zusammenführen
mein flixer
// 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);> >}> >}> }> |
>
Armstrong-Nummer
>Ausgabe:
Before operation : [1, 2, 3, 4, 5] After operation : [1, 2, 3, 30, 5] Replaced element : 4>
Beispiel 2: Für IndexOutOfBoundsException
rdbms-Normalisierung
// 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>Kapazität) '>);> >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);> >}> >}> }> |
>
>Ausgabe:
Before operation : [1, 2, 3, 4, 5] Trying to Replace the element at (index>Kapazität) Ausnahme ausgelöst: java.lang.IndexOutOfBoundsException: Index: 7, Größe: 5>