AdSense

AdSense3

Monday, 31 August 2015

Java List Interface

List Interface is the subinterface of Collection.It contains methods to insert and delete elements in index basis.It is a factory of ListIterator interface.

Commonly used methods of List Interface:

  1. public void add(int index,Object element);
  2. public boolean addAll(int index,Collection c);
  3. public object get(int Index position);
  4. public object set(int index,Object element);
  5. public object remove(int index);
  6. public ListIterator listIterator();
  7. public ListIterator listIterator(int i);

Java ListIterator Interface

ListIterator Interface is used to traverse the element in backward and forward direction.

Commonly used methods of ListIterator Interface:

  1. public boolean hasNext();
  2. public Object next();
  3. public boolean hasPrevious();
  4. public Object previous();

Example of ListIterator Interface:

  1. import java.util.*;  
  2. public class TestCollection8{  
  3. public static void main(String args[]){  
  4.   
  5. ArrayList<String> al=new ArrayList<String>();  
  6. al.add("Amit");  
  7. al.add("Vijay");  
  8. al.add("Kumar");  
  9. al.add(1,"Sachin");  
  10.   
  11. System.out.println("element at 2nd position: "+al.get(2));  
  12.   
  13. ListIterator<String> itr=al.listIterator();  
  14.   
  15. System.out.println("traversing elements in forward direction...");  
  16. while(itr.hasNext()){  
  17. System.out.println(itr.next());  
  18.  }  
  19.   
  20.   
  21. System.out.println("traversing elements in backward direction...");  
  22. while(itr.hasPrevious()){  
  23. System.out.println(itr.previous());  
  24.  }  
  25. }  
  26. }
Output:element at 2nd position: Vijay
       traversing elements in forward direction...
       Amit
       Sachin
       Vijay
       Kumar
       traversing elements in backward direction...
       Kumar
       Vijay
       Sachin
       Amit

No comments:

Post a Comment