Iterate elements of Java ArrayList using ListIterator.



import java.util.*;
 class A{
 public static void main(String as[]){

 ArrayList al = new ArrayList();

 al.add(new Integer(99))
 al.add("aa");
 al.add("bb");
 al.add("cc")
 al.add("dd");
  System.out.println(al);   // [99, aa, bb, cc, dd]
 al.add(0,"aaaa");
 al.add(2,"bbbb");
  System.out.println(al);   // [aaaa, 99, bbbb, aa, bb, cc, dd]
 al.remove(4);
  System.out.println(al);   // [aaaa, 99, bbbb, aa, cc, dd]
  System.out.println(al.get(2));  // bbbb

  System.out.println(al.indexOf("bbbb"));  // 2
  System.out.println(al.lastIndexOf("dd")); // 5
 al.set(0,"zz");
  System.out.println(al);    // [zz, 99, bbbb, aa, cc, dd]



 List list = al.subList(1,4);
  System.out.println(list);   // [99, bbbb, aa]
  System.out.println(list.getClass().getName()); // java.util.RandomAccessSubList

 System.out.println("Using listIterator - Forward :"); // Using listIterator - Forward :
 ListIterator li = al.listIterator();
 while(li.hasNext()){
    System.out.print(li.next()+"\t");  // zz 99 bbbb aa cc dd
  }
    System.out.println("");

 System.out.println("Using listIterator - Reverse :"); // Using  listIterator - Reverse :
 while(li.hasPrevious()){
    System.out.print(li.previous()+"\t");  // dd cc aa bbbb 99 zz
  }
    System.out.println("");



       //....... instead of while loop,we can use for loop.......

 
 System.out.println("Using listIterator - Forward1 :");  // Using listIterator - Forward1 :

 ListIterator it1;

 for(it1 =al.listIterator();it1.hasNext();){
  Object obj1=it1.next();
   System.out.print(obj1+"\t");   // zz 99 bbbb aa cc dd
  }
    System.out.println("");

 System.out.println("Using listIterator - Reverse1 :");  // Using  listIterator - Reverse1 :
 for(ListIterator it2 =al.listIterator(2);it2.hasPrevious();){
  Object obj2=it2.previous();
   System.out.print(obj2+"\t");
  // 99 zz     (bcoz Previous of 2nd index element are 1st index and zero index elements of list)
  }
    System.out.println("");


 String st = null;
 al.add(null);
 al.add(st);
  System.out.println(al);    // [zz, 99, bbbb, aa, cc, dd, null, null]
 }
 }

0 comments :

Post a Comment