Saturday, July 21, 2012

ArrayList in Java

Last time we discussed array in java and i told you that its a fixed size data structure. You have to tell the compiler the size of array. But what if you don't know how many data item you will have in future. The arralist is the answer. It is a dynamic data structure. You don't need to tell the size, just declare it and keep adding the item in arraylist. It grows or shrinks as you add or remove item from arraylist.
In java to use arraylist you must import the java.util package. Here is how you declare the arralist.

ArrayList al = new ArrayList();

Arraylist has many methods, Here I am telling few useful ones.

add():- This adds an item to arraylist. In () or as arguments we provide the element to be added. Yon can add as many item as you want.

get():- This method is used to retrieve back items from the arraylist. In () we mention the index of the arraylist (as you studied in array). We tell the locationof element and it sends the item back to us.

remove():- This item is used to delete an arraylist item. In () again we supply the index or location. After removal the arraylist gets shrink.

int size():- This method tells the size or number of arraylist items.

You can add the object of any class in arraylist too. Here i am using Student class which we are using through out our course.

Student S1 = new Student("mike", 20);
Student S2 = new Student("rachel", 22);

al.add(S1);
a2.add(S2);

Its very simple and fair to use arraylist and its methods. Another useful method is to check whether arraylist is empty or not. Ths "isEmpty()" method can be used. This method returns true or false according to arraylist condition.
So with this our lecture ends. Bye

No comments:

Post a Comment