Searching...
Saturday, 6 October 2012

Java Collections: ArrayList Example

04:07

·         Arraylist Uses an array to store the elements
·         In addition to the methods of the interface List it provides methods to manipulate the size of the array (e.g. ensureCapacity)
·         More efficient than LinkedList for methods involving indices – get(), set()
·         It is not synchronized
 
image
 

Example

package com.vinod.collections;

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

public class ArrayListExample {

    public static void main(String[] args) {
        List<String> aList = new ArrayList<String>();
        // Adding objects
        aList.add("1");
        aList.add("2");
        aList.add("3");
        aList.add("4");
        aList.add("5");
        System.out.println("ArrayList values : " + aList);
        System.out.println("Size : " + aList.size());
        // Remove elements from the array list
        aList.remove("1");
        aList.remove(3);
        System.out.println("ArrayList values after removal : " + aList);
        System.out.println("Size after removal : " + aList.size());
       
        //iterating
        for (String names : aList) {
            System.out.println("ArrayList values : " + names);
        }
    }

}
  

Output

ArrayList values : [1, 2, 3, 4, 5]

Size : 5

ArrayList values after removal : [2, 3, 4]

Size after removal : 3

ArrayList values : 2

ArrayList values : 3

ArrayList values : 4

0 comments: