Please explain the difference between the Vector.add() method and the Vector.addElement() method, along with a sample code snippet
views:
191answers:
4add() comes from the List interface, which is part of the Java Collections Framework added in Java 1.2. Vector predates that and was retrofitted with it. The specific differences are:
addElement()issynchronized.add()isn't. In the Java Collections Framework, if you want these methods to be synchronized wrap the collection inCollections.synchronizedList(); andadd()returns a boolean for success.addElement()has avoidreturn type.
The synchronized difference technically isn't part of the API. It's an implementation detail.
Favour the use of the List methods. Like I said, if you want a synchronized List do:
List<String> list = Collections.synchronizedList(new ArrayList<String>());
list.add("hello");
The javadoc mentions that:
public void addElement(E obj)
This method is identical in functionality to the add(E) method (which is part of the List interface).
The reason they both exist is (from the same javadoc):
As of the Java 2 platform v1.2, this class was retrofitted to implement the List interface, making it a member of the Java Collections Framework.
List has an add method, so an implementation was added to Vector, but to maintain backwards-compatibility, addElement wasn't removed
The method signature is different, add returns true, while addElement is void.
from http://www.docjar.com/html/api/java/util/Vector.java.html
153 public synchronized boolean add(E object) {
154 if (elementCount == elementData.length) {
155 growByOne();
156 }
157 elementData[elementCount++] = object;
158 modCount++;
159 return true;
160 }
and
223 public synchronized void addElement(E object) {
224 if (elementCount == elementData.length) {
225 growByOne();
226 }
227 elementData[elementCount++] = object;
228 modCount++;
229 }
addElement
This method is identical in functionality to the add(Object) method (which is part of the List interface).
So there is no difference between:
Vector v = new Vector();
v.addElement( new Object() );
and
Vector v = new Vector();
v.add( new Object() );
This class ( vector ) exists since Java1.0 and now is pretty much replaced by ArrayList which has the benefit of being slightly faster.