Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between Java's Vector.add() and Vector.addElement()?

Please explain the difference between the Vector.add() method and the Vector.addElement() method, along with a sample code snippet

like image 582
JavaUser Avatar asked Jun 22 '10 03:06

JavaUser


People also ask

What is the difference between ADD and addElement in Vector in java?

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.

Which class is used addElement () method in swing package?

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.

Which class is used addElement () method in swing package Mcq?

The addElement() method of Java Vector class is used to add the specified element to the end of this vector.

Which method add elements in Vector and returns Boolean type?

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.


2 Answers

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:

  1. 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

  2. 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");
like image 55
cletus Avatar answered Oct 05 '22 06:10

cletus


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       }
like image 21
Jubal Avatar answered Oct 05 '22 07:10

Jubal