1.Basic Java example program to insert element using list iterator to arraylist
Output:
- package com.javaIteratearraylistiterator;
- import java.util.ArrayList;
- import java.util.Collections;
- import java.util.Iterator;
- public class IterateListIteratorArrayList{
- public static void main(String[] args) {
- //create an ArrayList object
- ArrayList<String> arrayList = new ArrayList();
- //Add elements to Arraylist
- arrayList.add("A");
- arrayList.add("B");
- arrayList.add("C");
- arrayList.add("D");
- arrayList.add("F");
- arrayList.add("F");
- arrayList.add("G");
- arrayList.add("H");
- arrayList.add("I");
- /*
- Get a ListIterator object for ArrayList using
- istIterator() method.
- */
- System.out.println("Before inserting element");
- for(int intIndex = 0; intIndex < arrayList.size(); intIndex++)
- System.out.println(arrayList.get(intIndex));
- ListIterator itr = arrayList.listIterator();
- /*
- Use void add(Object o) method of ListIterator to add or insert an element
- to List. It adds an element just before the element that would have
- been returned by next method call and after the element that would have
- returned by previous call.
- */
- itr .next();
- //Add an element
- itr .add("Added Element");
- /*
- System.out.println("After inserting element .");
- for(int intIndex = 0; intIndex < arrayList.size(); intIndex++)
- System.out.println(arrayList.get(intIndex));
- }
- }
Output:
- Before inserting element
- A
- B
- C
- D
- F
- F
- G
- H
- I
- After inserting element .
- A
- Added Element
- B
- C
- D
- F
- F
- G
- H
- I
Bagikan
Java program to insert an element to ArrayList using ListIterator Example
4/
5
Oleh
Kris Kimcil