Tuesday, 5 June 2012

Java List and ArrayList


What is Difference between List and ArrayList
For the handling of objects collection in Java, Collection interface have been provided.
This is avail in java.util package.

"List" is an interface, extends collection interface, provides some sort of extra methods
than collection interface to work with collections. Where as "ArrayList" is the actual
implementation of "List" interface.

So both the following are correct
List x= new ArrayList(); or ArrayList x= new ArrayList();


List:
List is an interface in collection framework. several classes like ArrayList,
LinkedList implement this interface. List is an ordered collection ,
so the position of an object does matter.

ArrayList:
An ArrayList is a class which can grow at runtime. you can store java objects in an ArrayList
and also add new objects at run time.
you will use ArrayList when you dont have to add or remove objects frequently from it.
Because when you remove an object, all other objects need to be repositioned inside the ArrayList,
if you have this kind of situation, try using LinkedList instaed.


Example:
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;   public class ArrayToList {
     public static void main(String[] argv) {   String sArray[] = new String[] { "Array 1", "Array 2", "Array 3" };   // convert array to list
 List<String> lList = Arrays.asList(sArray);   // iterator loop
 System.out.println("#1 iterator");
 Iterator<String> iterator = lList.iterator();
 while (iterator.hasNext()) {
  System.out.println(iterator.next());
 }   // for loop
 System.out.println("#2 for");
 for (int i = 0; i < lList.size(); i++) {
  System.out.println(lList.get(i));
 }   // for loop advance
 System.out.println("#3 for advance");
 for (String temp : lList) {
  System.out.println(temp);
 }   // while loop
 System.out.println("#4 while");
 int j = 0;
 while (j < lList.size()) {
  System.out.println(lList.get(j));
  j++;
 }
    }
}



import java.util.Iterator;
import java.util.List;
import java.util.ArrayList;

public class ListExample {

    public static void main(String[] args) {

        // List Example implement with ArrayList
        List<String> ls=new ArrayList<String>();

        ls.add("one");
        ls.add("Three");
        ls.add("two");
        ls.add("four");

        Iterator it=ls.iterator();

        while(it.hasNext())
        {
          String value=(String)it.next();

          System.out.println("Value :"+value);
        }
    }
}

No comments:

Post a Comment