Friday, 22 January 2016

Collections -- ArrayList

public class ArrayLists {

    public static void main(String[] args) {
        ArrayList<String> als = new ArrayList<String>();
       
       
        als.add("Name1");
        als.add("Name2");
        als.add("Name3");
        als.add("Name4");
        als.add("Name5");
        als.add("Name5");
       
        Iterator itr = als.iterator();
        while(itr == itr.next())
        {
            System.out.println(itr.next());
        }
       
        }
       
       

    }


in place of iterator we can use for loop also.... it is up to you how you use the traditional for loop or new for loop syntax.

for example:

public class ArrayLists {

    public static void main(String[] args) {
        ArrayList<String> als = new ArrayList<String>();
       
       
        als.add("Name1");
        als.add("Name2");
        als.add("Name3");
        als.add("Name4");
        als.add("Name5");
        als.add("Name5");
       
       for(String alsObject : ls)
        {
         System.out.println(alsObject);
         }
        }
       
       

    }

here the array list is the in memory data structure.
it can contain duplicate values.
its an dynamic array(same as arrays concept).
the add() method adds the values to the array list, later they can be retrieved by using iterator.
random access of the values or the objects is possible.
it is slow compared to other collection data structures
note: Collection framework is a generic one.......

No comments:

Post a Comment