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>();
Ex:-
ArrayList<File> al=new ArrayList<File>();
We can use any Object type here.
To add in ArrayList at last:-
al.add(f);
This appends an Object 'f' at end of ArrayList.
To add in specific position:-
al.add(index,f);
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:-
al.remove(index);
To remove all items:-
al.clear();
To replace an item with another item at specific index:-
al.set(index,f);
where f is object type of which ArrayList has been made.
No comments:
Post a Comment
Write Your Comments..