Friday, December 17, 2010

Java Collection - ArrayList

ArrayList is one of the most powerful java data structure. It lies on java.util package.
You can instantiate it:

>> ArrayList alNames = new ArrayList();

Then after that, you can add element to the object

>> alNames.add("luna maya");
>> alNames.add("lady gaga");

To access an element in ArrayList, you use the index:

>> alNames.get(0);

To remove an element from arrayList, you can one either of:
>> alNames.remove("luna maya");
>> alNames.remove(0);

To get to know, how many elements in alNames, you use
>> int count = alNames.size();

There is also one so powerful method that return alNames as an Array:
>> Object obj[] = alNames.toArray();

For intention to iterate through all elements of the ArrayList, use iterator instead of conventional looping:
>> Iterator ite = alNames.iterator();
>> while(ite.hasNext()){
>>    String s =      // Use Object as general
>>    System.out.println(s);
>> }


1 comment:

  1. Java has been touted as probably the best platform to write programs on so

    they run on various different machines. MIDIlets are basically Java

    programs that run on smartphones like Nokia, To learn more visit:

    java training