Tuesday, August 9, 2016

ArrayList Quick Reference

It’s a Resizable-array implementation of the List interface
permits all elements, including null
equivalent to Vector, except that it is unsynchronized( i.e. it’s methods are unsynchronized)
Following operations run in constant timeget, set, iterator, listIterator
In case of add operation, adding n elements requires O(n) time
In multi-threaded environment, to prevent accidental unsynchronized access to the ArrayList  that can modify ArrayList structurally, wrap ArrayList using Collections.synchronizedList
List list = Collections.synchronizedList(new ArrayList(...));
The iterators returned by this class's iterator() and listIterator(int) methods are fail-fast if the list is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove() or add(Object) methods, the iterator will throw a ConcurrentModificationException.
Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. But one must not write program that depends on this behaviour.
ArrayList internally implements growable dynamic array which means it can increase and decrease its size automatically. If we try to add an element to a already full ArrayList then it automatically re-sized internally to accommodate the new element
Consider a scenario when there is a need to add huge number of elements to an already full ArrayList, in such case ArrayList has to be resized several number of times which would result in a poor performance. For such scenarios ensureCapacity() method of ArrayList class is very useful as it increases the size of the ArrayList by a specified capacity.
public void ensureCapacity(int minCapacity)

toArray() mathod returns an array containing all of the elements in this list in proper sequence (from first to last element).So, this method acts as bridge between array-based and collection-based APIs.
remove(int index) method removes the element at the specified position(index) in this list. Shifts any subsequent elements to the left and return the element that was removed from the list
remove(Object o) method removes the first occurrence of the specified element from this list, if it is present and return true if this list contained the specified element else return false.

No comments:

Total Pageviews