Please explain the difference between the Vector.add() method and the Vector.addElement() method, along with a sample code snippet
What is difference between add() and addElement() in Vector? - The add() methods inserts an element at a given position of the vector. - The addElement () method adds an object at the end of the vector and increases the size of the vector by one.
addElement() method is used to append a specified element to the end of this vector by increasing the size of the vector by 1. The functionality of this method is similar to that of the add() method of Vector class.
The addElement() method of Java Vector class is used to add the specified element to the end of this vector.
boolean add(Object element): This method appends the specified element to the end of this vector. Parameters: This function accepts a single parameter element as shown in the above syntax. The element specified by this parameter is appended to end of the vector.
add() 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() is synchronized. add() isn't. In the Java Collections Framework, if you want these methods to be synchronized wrap the collection in Collections.synchronizedList(); and
add() returns a boolean for success. addElement() has a void return 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 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       }
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With