If there is a need to update the list element based on the index then set method of ArrayList class can be used. The method set(int index, Element E) updates the element of specified index with the given element E.
public E set(int index, Element E)
Example:
In this example I have an ArrayList of Integer Type where I have added few elements and then I’m updating few of elements using set method of java.util.ArrayList
class.
package beginnersbook.com; import java.util.ArrayList; public class SetExample { public static void main(String args[]) { ArrayList<Integer> arraylist = new ArrayList<Integer>(); arraylist.add(1); arraylist.add(2); arraylist.add(3); arraylist.add(4); arraylist.add(5); arraylist.add(6); arraylist.add(7); System.out.println("ArrayList before update: "+arraylist); //Updating 1st element arraylist.set(0, 11); //Updating 2nd element arraylist.set(1, 22); //Updating 3rd element arraylist.set(2, 33); //Updating 4th element arraylist.set(3, 44); //Updating 5th element arraylist.set(4, 55); System.out.println("ArrayList after Update: "+arraylist); } }
Output:
ArrayList before update: [1, 2, 3, 4, 5, 6, 7] ArrayList after Update: [11, 22, 33, 44, 55, 6, 7]
Leave a Reply