Tuesday, April 28, 2015

ArrayList vs Vector

Similarities
  1. Both allows null and duplicates and index based and backed up by an array internally.
  2. Both are derived from AbstractList and implements List interface.
  3. Both can be iterated with Iterator or ListIterator.
       Get the Enumeration object:
     - Enumeration e = Collections.enumeration(arrayList);
    - Vector can return enumeration of items it hold by calling elements () method.
  4. Both are fail-fast.
    The iterators returned by this class's iterator and listIterator 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 methods, the iterator will throw a ConcurrentModificationException.

Differences
  1. Vector is synchronized but ArrayList is not.
  2. Whenever Vector crossed the threshold specified it increases itself by value specified in capacityIncrement field while you can increase size of ArrayList by calling ensureCapacity () method.
  3. Vector standard initial size is 10,standard  capacityIncrement is zero
    The size of the new data array will be the old size plus capacityIncrement, unless the value of capacityIncrement is less than or equal to zero, in which case the new capacity will be twice the old capacity; but if this new size is still smaller than minCapacity, then the new capacity will be minCapacity.
  4. ArrayList starts with a default initial capacity of 10,
  5. Java 1.7  ==>  int newCapacity = oldCapacity + (oldCapacity >> 1)
    Java 6 ====>    int newCapacity = (oldCapacity * 3)/2 + 1;
  6. Vector provides a method to get the current capacity but ArrayList doesn't ).
It would be wrong to write a program that depended on this exception for its correctness, the fail-fast behavior of iterators should be used only to detect bugs.

If a thread-safe implementation is not needed, it is recommended to use ArrayList in place of Vector.

https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html
http://docs.oracle.com/javase/7/docs/api/java/util/Vector.html

No comments:

Post a Comment

java - fill distinct objects in ArrayList

If you have a list that contains some objects that it is considered as duplication when two or three fields of these objects are equal. How ...