Jumat, 11 Maret 2016

Java program to insert an element to ArrayList using ListIterator Example

1.Basic Java example program to insert element using list iterator to arraylist
  1. package com.javaIteratearraylistiterator;
  2.  
  3. import java.util.ArrayList;
  4. import java.util.Collections;
  5. import java.util.Iterator;
  6.  
  7. public class IterateListIteratorArrayList{
  8.  
  9. public static void main(String[] args) {
  10.   
  11. //create an ArrayList object
  12. ArrayList<String> arrayList = new ArrayList();
  13.        
  14. //Add elements to Arraylist
  15.  
  16. arrayList.add("A");
  17. arrayList.add("B");
  18. arrayList.add("C");
  19. arrayList.add("D");
  20. arrayList.add("F");
  21. arrayList.add("F");
  22. arrayList.add("G");
  23. arrayList.add("H");
  24. arrayList.add("I");
  25.     
  26.         
  27.  /*
  28. Get a ListIterator object for ArrayList using
  29. istIterator() method.
  30. */
  31.   
  32. System.out.println("Before inserting element");
  33.  
  34. for(int intIndex = 0; intIndex < arrayList.size(); intIndex++)
  35.               System.out.println(arrayList.get(intIndex)); 
  36. ListIterator itr = arrayList.listIterator();
  37.        
  38. /*
  39.       Use void add(Object o) method of ListIterator to add or insert an element
  40.       to List. It adds an element just before the element that would have
  41.       been returned by next method call and after the element that would have
  42.       returned by previous call.
  43.     */
  44.    
  45.     itr .next();
  46.        
  47.     //Add an element
  48.     itr .add("Added Element");
  49.     /*
  50.  
  51. System.out.println("After inserting element .");
  52.  
  53. for(int intIndex = 0; intIndex < arrayList.size(); intIndex++)
  54.               System.out.println(arrayList.get(intIndex));   
  55.  
  56. }
  57. }
     



Output:

  1. Before inserting element
  2. A
  3. B
  4. C
  5. D
  6. F
  7. F
  8. G
  9. H
  10. I
  11. After inserting element .
  12. A
  13. Added Element
  14. B
  15. C
  16. D
  17. F
  18. F
  19. G
  20. H
  21. I

Bagikan

Jangan lewatkan

Java program to insert an element to ArrayList using ListIterator Example
4/ 5
Oleh

Subscribe via email

Suka dengan artikel di atas? Tambahkan email Anda untuk berlangganan.