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 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.

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.

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()) {
 }   // for loop
 System.out.println("#2 for");
 for (int i = 0; i < lList.size(); i++) {
 }   // for loop advance
 System.out.println("#3 for advance");
 for (String temp : lList) {
 }   // while loop
 System.out.println("#4 while");
 int j = 0;
 while (j < lList.size()) {

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>();


        Iterator it=ls.iterator();

          String value=(String)it.next();

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

No comments:

Post a Comment

Passing Parameter between two files using MVVM

This examples shows how to pass parameter between two zul screens. In this example, we are passing some parameters from the parent vm to...