logo

Metoda ArrayList set() v Javi s primeri

The set() metoda java.util.ArrayLis t razred se uporablja za zamenjavo elementa na podanem mestu na tem seznamu s podanim elementom.

Sintaksa:



public E set(int index, E element)>

Parametri: Ta metoda sprejme naslednji argument kot parameter.

    index- indeks elementa za zamenjavo element- element, ki bo shranjen na določenem mestu

Vrne vrednost: Ta metoda vrne element prej na določenem mestu.

Izjema: Ta metoda vrže IndexOutOfBoundsException če indeks ni v obsegu velikosti seznama ArrayList.



Spodaj so primeri za ponazoritev set() metoda.

Primer 1:

java povratni niz






// 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);> >}> >}> }>

kaj je sklad java
>

bdrevo in b drevo
>

Izhod:

 Before operation : [1, 2, 3, 4, 5] After operation : [1, 2, 3, 30, 5] Replaced element : 4>

Primer 2: Za IndexOutOfBoundsException




model tcp ip

// 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>Zmogljivost) '>);> >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);> >}> >}> }>

>

>

Izhod:

 Before operation : [1, 2, 3, 4, 5] Trying to Replace the element at (index>Kapaciteta) Vržena izjema: java.lang.IndexOutOfBoundsException: Indeks: 7, Velikost: 5>