ArrayList

  1. The underlying data structure is resizable array and grow able array.
  2. Duplicates are allowed.
  3. Insertion order is preserved.
  4. Heterogeneous objects are allowed [except TreeSet and TreeMap]
  5. Null insertion is possible.

ArrayList Constructors

  • ArrayList list = new ArrayList();

Creates an empty array list object with default initial capacity. Once array list reaches its maximum capacity a new array list will be created with new capacity.

New capacity = (Current Capacity*3/2)+1 which is almost 75%

            With the above mentioned constructor Arraylist with default size i.e. 10 will be created and once it reaches its maximum capacity then it grows dynamically with new capacity i.e. 15.

  • ArrayList list = new ArrayList(int initial capacity);

Creates an empty array list object with the given initial capacity. Once array list reaches its maximum capacity a new array list will be created with new capacity.

  • ArrayList list = new ArrayList(Collection c)

Creates an array list object for the given collection.

Example

package List;

import java.util.ArrayList;

public class ArrayListDemo {
	public static void main(String[] args) {
		ArrayList l = new ArrayList();
		l.add("A");
		l.add("10");
		l.add("A");
		l.add("null");
		System.out.println(l); // [A, 10, A, null]
		l.remove(2);
		System.out.println(l); // [A, 10, null]
		l.add(2, "M");
		l.add("N");
		System.out.println(l); // [A, 10, M, null, N]

	}

}

6. Usually we can use collection to hold and transfer objects over the network and to support this requirement every collection already implements Serializable and Cloneable.

7. ArrayList and vector classes implements RandomAccess interface so that we can access any random element with the same speed.

package List;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.RandomAccess;

public class ArrayListSerialClone {

	public static void main(String[] args) {
		ArrayList l1 = new ArrayList();
		LinkedList l2 = new LinkedList();
		System.out.println(l1 instanceof Serializable); // true
		System.out.println(l1 instanceof Cloneable); // true

		System.out.println(l2 instanceof Serializable); // true
		System.out.println(l2 instanceof Cloneable); // true

		System.out.println(l1 instanceof RandomAccess); // true
		System.out.println(l2 instanceof RandomAccess); // false

	}
}

8. Hence if our frequent operation is retrieval operation then ArrayList is the best choice.

9. ArrayList is the worst choice if our frequent operation is insertion or deletion in the middle(Because several shift operations will be required).

236 total views, 2 views today