Sunday, July 12, 2009

Tutorial on how to use ArrayList

Many times , it is essential that we need to update the arrays which we have defined in our code.
However arrays are defined with a fixed size so they cannot be updated to larger size dynamically.
Some may use the trick of copying the contents of array to a new array of bigger size.
But we also have a nice way of getting this feature of dynamically updating arrays through ArrayList.

To define ArrayList object:-

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

ArrayList<File> al=new ArrayList<File>();
We can use any Object type here.

To add in ArrayList at last:-
This appends an Object 'f' at end of ArrayList.

To add in specific position:-

To find size of ArrayList:-
int size=al.size();

To get an item at any specific position in ArrayList:-
f=al.get(index); //Here index is a integer from 0 to size-1
Here f is the Object Type of which we make the ArrayList.
If we make it of File type then al.get(index) will return a File type Object.

To remove an item at specific position:-

To remove all items:-

To replace an item with another item at specific index:-
where f is object type of which ArrayList has been made.

No comments:

Post a Comment

Write Your Comments..

Share this Page:-