In this tutorial we will see about Vector and ArrayList in java. Both Vector and ArrayList shares common data structure "Array" internally.
Synchronized and non-synchronized
By default Vector is Synchronized and ArrayList is not Synchronized. By this for Thread safe we can use Vector and for non-thread safe we can use ArrayList. Even ArrayList can be converted to synchronized by Collections class using "Collections.synchronizedList(list)"
Vector in Collection API
Vector defined in first JDK version and later from Java 2 platform Vector got added with Java Collection API. Vector has been retrofitted to implement List Interface.
Once Vector added in Collection API, older methods in Vector class got updated to implement List Interface. Below are the methods got updated from Older version to new methods.
Where to use Vector and ArrayList
By performance wise ArrayList will be better in case of non synchronized operations and when we need for thread-safe operation then we need to opt for Vector.
Size
Both Vector and ArrayList will re-size dynamically. Vector will double the size of its array automatically when its full, where as ArrayList will increase by half of its array size.
Synchronized and non-synchronized
By default Vector is Synchronized and ArrayList is not Synchronized. By this for Thread safe we can use Vector and for non-thread safe we can use ArrayList. Even ArrayList can be converted to synchronized by Collections class using "Collections.synchronizedList(list)"
Vector in Collection API
Vector defined in first JDK version and later from Java 2 platform Vector got added with Java Collection API. Vector has been retrofitted to implement List Interface.
Once Vector added in Collection API, older methods in Vector class got updated to implement List Interface. Below are the methods got updated from Older version to new methods.
Old Vector Methods | New Vector Methods |
---|---|
void addElement(Object) | boolean add(Object) |
boolean removeElement(Object) | boolean remove(Object) |
void removeElementAt(int) | void remove(int) |
void insertElementAt(Object, int) | void add(index, Object) |
Object elementAt(int) | Object get(int) |
Enumeration elements() | Iterator iterator() ListIterator listIterator() |
void copyInto(Object[]) | Object[] toArray() |
void removeAllElements() | void clear() |
void setElementAt(int) | Object set(int, Object) |
Where to use Vector and ArrayList
By performance wise ArrayList will be better in case of non synchronized operations and when we need for thread-safe operation then we need to opt for Vector.
Size
Both Vector and ArrayList will re-size dynamically. Vector will double the size of its array automatically when its full, where as ArrayList will increase by half of its array size.
No comments:
Write comments