Metoda ArrayList set() w Javie z przykładami
The ustawić() metoda java.util.ArrayLis T class służy do zastąpienia elementu znajdującego się na określonej pozycji na tej liście określonym elementem.
Składnia:
public E set(int index, E element)
Parametry: Ta metoda przyjmuje następujący argument jako parametr.
- indeks – indeks elementu do zastąpienia – element, który ma być zapisany na określonej pozycji
Zwraca wartość: Ta metoda zwraca element wcześniej na określonym stanowisku.
Wyjątek: Ta metoda rzuca Wyjątek IndexOutOfBounds jeśli indeks nie mieści się w zakresie wielkości ArrayList.
Poniżej znajdują się przykłady ilustrujące ustawić() metoda.
Przykład 1:
// 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);> > }> > }> }> |
Wyjście:
Before operation : [1, 2, 3, 4, 5] After operation : [1, 2, 3, 30, 5] Replaced element : 4
Przykład 2: Dla Wyjątek 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>Pojemność) '> );> > 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);> > }> > }> }> |
Wyjście:
Before operation : [1, 2, 3, 4, 5] Trying to Replace the element at (index>Pojemność) Zgłoszono wyjątek: java.lang.IndexOutOfBoundsException: Indeks: 7, Rozmiar: 5