1. package com.instanceofjavaforus;
  2. import java.util.ArrayList;
  3.  
  4. public class AddElementAtSpecifiedIndex {
  5.  
  6.     public static void main(String[] args) {
  7.  
  8.        //create an ArrayList object
  9.         ArrayList arrayList = new ArrayList();
  10.  
  11.         //Add elements to Arraylist
  12.         arrayList.add("a");
  13.         arrayList.add("b");
  14.         arrayList.add("c");
  15.         arrayList.add("d");
  16.         arrayList.add("f");
  17.         arrayList.add("g");
  18.  
  19.         arrayList.add(1,"Y");
  20.  
  21.         System.out.println("ArrayList values...");
  22.  
  23.         //display elements of ArrayList
  24.         for(int index=0; index < arrayList.size(); index++)
  25.           System.out.println(arrayList.get(index));
  26.        arrayList.add(2,"Z");
  27.  
  28.     System.out.println("ArrayList values...");
  29.  
  30.         //display elements of ArrayList
  31.        for(int index=0; index < arrayList.size(); index++)
  32.           System.out.println(arrayList.get(index));
  33.       }
  34.  
  35. }
  36. }
     

  1. OutPut:
  2. ArrayList values...
  3. a
  4. Y
  5. b
  6. c
  7. d
  8. f
  9. g
  10. ArrayList values...
  11. a
  12. Y
  13. Z
  14. b
  15. c
  16. d
  17. f
  18. g
     

Instance Of Java

We are here to help you learn! Feel free to leave your comments and suggestions in the comment section. If you have any doubts, use the search box on the right to find answers. Thank you! 😊
«
Next
Sort ArrayList in descending order
»
Previous
String vs stringbuffer vs stringbuilder

No comments

Leave a Reply

Select Menu