El colocar() método de java.util.ArrayLis t La clase se utiliza para reemplazar el elemento en la posición especificada en esta lista con el elemento especificado.
Sintaxis:
public E set(int index, E element)>
Parámetros: Este método toma el siguiente argumento como parámetro.
- índice- índice del elemento a reemplazar elemento- elemento que se almacenará en la posición especificada
Valor devuelto: Este método devuelve el elemento previamente en la posición especificada.
Excepción: Este método arroja Excepción IndexOutOfBounds si el índice no está dentro del rango de tamaño de ArrayList.
A continuación se muestran ejemplos para ilustrar la colocar() método.
Ejemplo 1:
ridhima tiwari
// 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);> >}> >}> }> |
la cadena java contiene
>
lista de látex
>Producción:
Before operation : [1, 2, 3, 4, 5] After operation : [1, 2, 3, 30, 5] Replaced element : 4>
Ejemplo 2: Para Excepción IndexOutOfBounds
// 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>Capacidad) '>);> >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);> >}> >}> }> |
si no, declaración en java
>
>Producción:
Before operation : [1, 2, 3, 4, 5] Trying to Replace the element at (index>Capacidad) Excepción lanzada: java.lang.IndexOutOfBoundsException: Índice: 7, Tamaño: 5>