All for Joomla All for Webmasters

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. ArrayList<String> al=new ArrayList<String>();
  5. al.add(“Amit”);
  6. al.add(“Vijay”);
  7. al.add(“Kumar”);
  8. al.add(1,“Sachin”);
  9. System.out.println(“element at 2nd position: “+al.get(2));
  10. ListIterator<String> itr=al.listIterator();
  11. System.out.println(“traversing elements in forward direction…”);
  12. while(itr.hasNext()){
  13. System.out.println(itr.next());
  14.  }
  15. System.out.println(“traversing elements in backward direction…”);
  16. while(itr.hasPrevious()){
  17. System.out.println(itr.previous());
  18.  }
  19. }
  20. }
Output:element at 2nd position: Vijay
       traversing elements in forward direction...
       Amit
       Sachin
       Vijay
       Kumar
       traversing elements in backward direction...
       Kumar
       Vijay
       Sachin
       Amit
PinIt
submit to reddit

Leave a Reply

Top