» » » Basic Java example program to replace an element at specified index arraylist

1.Basic java Example program to replace an element at specified index java arrayList.

  1. package com.instanceofjavaforus;
  2. import java.util.ArrayList;
  3.  
  4. public class ReplaceArrayList{
  5.  
  6. public static void main(String[] args) {
  7.   
  8. //create an ArrayList object
  9.  ArrayList<Integer> arrayList = new ArrayList<Integer>();
  10.        
  11.         //Add elements to Arraylist
  12.         arrayList.add(1);
  13.         arrayList.add(2);
  14.         arrayList.add(3);
  15.         arrayList.add(4);
  16.         arrayList.add(5);
  17.         arrayList.add(6);
  18.         arrayList.add(7);
  19.         arrayList.add(8);
  20.         arrayList.add(9);
  21.         arrayList.add(10);
  22.         
  23.  
  24.   /*
  25.   To replace an element at the specified index of ArrayList use
  26.   Object set(int index, Object obj) method.
  27.   This Object set(int index, Object obj) method replaces the specified element at the specified
  28.   index in the ArrayList and returns the element previously at the specified position.
  29.   */
  30.  
  31.  arrayList.set(1,23);
  32.      
  33.  System.out.println("ArrayList contains...");
  34.  Iterator itr=arrayList.iterator();
  35.  
  36. while (itr.hasNext()) {
  37.  
  38.  System.out.println(itr.next());
  39.  
  40.  }
  41.   
  42. }
  43. }
     



Output:

  1. ArrayList contains...
  2. 1
  3. 23
  4. 3
  5. 4
  6. 5
  7. 6
  8. 7
  9. 8
  10. 9
  11. 10

Instance Of Java

We will help you in learning.Please leave your comments and suggestions in comment section. if you any doubts please use search box provided right side. Search there for answers thank you.
«
Next
Newer Post
»
Previous
Older Post

No comments

Leave a Reply

Select Menu