threads
Vector copy example
With this example we are going to demonstrate how to get a copy of a Vector. We are using the synchronized
statement in order to take a safe copy of the Vector’s elements. In short, to get a copy of a Vector you should:
- Create a new Vector.
- Populate the vector with elements, using
addElement(Object obj)
API method of Vector. - Set the Vector in a
synchronized
statement. - Create a new String array with the size equal to the Vector.size().
- Get each one of the Vector’s elements, using
elementAt(int index)
API method of Vector and put it in the same index of the array.
Let’s take a look at the code snippet that follows:
package com.javacodegeeks.snippets.core; import java.util.Vector; public class VectorCopyExample { public static void main(String[] args) { Vector vector = new Vector(); vector.addElement("JavaCodeGeeks"); vector.addElement("is"); vector.addElement("Cool!"); String[] wordArray; synchronized (vector) { int size = vector.size(); wordArray = new String[size]; for (int i = 0; i < wordArray.length; i++) { wordArray[i] = (String) vector.elementAt(i); } } System.out.println("word.length" + wordArray.length); for (int i = 0; i < wordArray.length; i++) { System.out.println("[" + i + "]=" + wordArray[i]); } } }
Output:
word.length3
[0]=JavaCodeGeeks
[1]=is
[2]=Cool!
This was an example of how to get a copy of a Vector in Java.