Tuesday, January 14, 2020

Difference between ArrayList and Vector in Java

ArrayList & vector both use Array data structure internally. Both  ArrayList & vector can grow and shrink dynamically and maintains the insertion order. Vector is legacy class present since JDK 1.0 and ArrayList was introduced in JDK 1.2 as part of collection framework. Both implement the List interface 

Resizable – ArrayList & Vector both can grow and shrink but there is one basic difference between them ArrayList will increase 50% of its original size while Vector will increase 100% means double of its original size if elements exceeds its capacity.

ArrayList:
·         Initial Capacity:10
·         Load Factor:1 (when the list is full)
·         Growth Rate: current_size + current_size/2
Vector:
·         Initial Capacity:10
·         Load Factor:1 (when the list is full)
·         Growth Rate: current_size * 2 (if capacityIncrement is not defined) current_size + capacityIncrement (if capacityIncrement is defined during vector initialization)

ThreadSafe- aAraylist is not synchronized hence it’s not thread safe means multiple thread can access ArrayList on same time like if one thread adding element to ArrayList while other can read the elements in ArrayListor can delete the element in ArrayList but in case of Vector it is synchronized means its thread safe so only one thread can access Vector at time. All methods in Vector are synchronized.

Performance- Performance wise ArrayList is faster compare to Vector because array list is not synchronized hence multiple thread can access ArrayList at time but Vector is synchronized hence thread will get lock on Vector and another thread have to wait until lock released.

Iteration- For vector we can use Iterator,ListIterator and Enumeration interface to iterate over elements in Vector but for ArrayList we can use only Iterator & ListIterator interface to iterate over elements in ArraytList

ConcurrentModificationException- iterator and listIterator returned by( ArrayList,Vector) are fail-fast means 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. 

No comments:

Post a Comment