Sunday, March 17, 2013

Java ArrayList Example

Java ArrayList Example :

Java ArrayList Example, I am giving very straight, short and easy description, you can straight away use this in your Code.

ArrayList : You can find this ArrayList class in java.util package. There are lot of methods available to manipulate ArrayList Object.

The advantage of ArrayList is to store the different kind of objects, either string or user defined class objects.

In the below i am giving the ArrayList Example how you can store the String Objects and again get the objects from that ArrayList object.

Here i am giving the two ways two get the Elements from the ArrayList object,

1) Get the elements from the ArrayLsit  by using Iterator.
2) Get the elements from the ArrayLsit  by using For Loop.


ArrayList Example 

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

public class ArrayListExample {
    @SuppressWarnings("unchecked")
    public static void main(String[] args) {
        @SuppressWarnings("rawtypes")
        // Create an ArrayList Object and add the elements into it.
        ArrayList aList = new ArrayList();
        // Add the String objects in the ArrayList
        aList.add("Test1");
        aList.add("Test2");
        aList.add("Test3");
        // Get the Elements from the ArrayList
        @SuppressWarnings("rawtypes")
        Iterator itr = aList.iterator();
        System.out
                .println("Using Iterator to get the Elememts from the ArrayList: ");
        while (itr.hasNext()) {
            System.out.println((String) itr.next());
        }
        // Another Way To get the elements from the ArrayList
        System.out
                .println("Using for Loop to get the Elememts from the ArrayList: ");
        for (int i = 0; i < aList.size(); i++) {
            System.out.println((String) aList.get(i));
        }
    }
}



OutPut :

Using Iterator to get the Elements from the ArrayList:
Test1
Test2
Test3
Using for Loop to get the Elements from the ArrayList:
Test1
Test2
Test3


0 comments:

Post a Comment

 
Disclaimer : If you find any mistakes / corrections / feedback Please let us know...This website author shall not accept liability or responsibility for any errors, mistakes or misstatements found in this website.