Java ArrayList

Ok today we gonna talk about Java Array List. Array List is very similar to array and we can store elements sequentially and access elements by indexed position. But the main difference between Array and Array List is, Array List is dynamic. It means It’s size can grow and shrink. but Array have a fixed size. OK got it? ūüôā It was a simple definition of Array List. Let’s know more about Array List.

Let’s look a simple code

import java.util.*;

class AList{
          public static void main(String args[]){
 ArrayList<String> al=new ArrayList<String>();//creating arraylist
 al.add("somba");//adding object in arraylist

Iterator itr=al.iterator();//getting Iterator from arraylist to traverse elements
   while(itr.hasNext()){   //also we can use for loop for traverse elements

In this code first we have imported java.util.* or we can import just java.util.ArrayList  class.

ArrayList<String> al=new ArrayList<String>();

Here we create new Array List object “al” and we give the object type as a String. If you want to create an Integer ArrayList you can do like this.

ArrayList<Integer> al=new ArrayList<Integer>();

Here we put “Integer” ¬†integer class and not a “int” premitive.

Why we use ArrayList ?
* It can grow dynamically.
* It provides more powerful insertion and search mechanisms than arrays.
* Java ArrayList class is non synchronized.

when we talk about arrayList, I think we should consider about Genaric collection.
Now you will see what is genaric. ūüôā

Before genaric is introduced we can store any type of objects in collection. It means non-generic. But in “genarics” , forces java programmer to ¬† store specific type of objects.

Before genarics, here we have to do type casting.

List list = new ArrayList();
String s = (String) list.get(0);//typecasting

After genarics, here we don’t need to typecast the object.

List<String> list = new ArrayList<String>();
String s = list.get(0);

In generic collection, we specify the type in angular braces. Now ArrayList is forced to have only specified type of objects in it. If you try to add another type of object, it gives compile time error.