1

When I use these lines:

vector.set(i, copyedVector.clone());

vector holds Vector<String>

copyVector holds strings

It gives me an error when I use clone. But when I remove clone, it works fine. How do I make a copy of a vector into the other vector?

Enamul Hassan
  • 5,266
  • 23
  • 39
  • 56
user1670252
  • 47
  • 1
  • 1
  • 8
  • From what you're saying, each element in your `Vector` holds a `Vector` of `String`s? If you're `Vector` is actually just a list of `String`s you should use [`Vector.addAll(Collection)`](http://docs.oracle.com/javase/7/docs/api/java/util/Vector.html#addAll%28java.util.Collection%29) which will copy each element from source `Vector` into this one...? – MadProgrammer Sep 25 '12 at 03:15
  • FYI, you probably would be better off using a different collection type rather than `Vector` (e.g. `ArrayList`). See [Why is Java Vector class considered obsolete or deprecated?](http://stackoverflow.com/questions/1386275/why-is-java-vector-class-considered-obsolete-or-deprecated) – DaoWen Sep 25 '12 at 05:15

4 Answers4

2

As others have pointed out, it is not clear if you "vector" variable is a Vector of Vectors (Vector<Vector<String>>) or simply a Vector of Strings (Vector<String>). Please see the following code snippet.

Vector<String> destVector = new Vector<String>();
Vector<String> sourceVector = new Vector<String>();
sourceVector.add("A");
sourceVector.add("B");
sourceVector.add("C");
destVector.addAll(0,sourceVector);

// If your target vector is a vector of vectors (of strings)
Vector<Vector<String>> destVector2 = new Vector<Vector<String>>();
destVector2.set(0,(Vector<String>)sourceVector.clone());

Also, please note that the clone method returns an Object. So you will have to explicitly cast to your desired data type.

Luhar
  • 1,859
  • 2
  • 16
  • 23
0

Not sure if this is exactly what you are asking but if you want to copy all the element you can use the addAll method and pass the vector to copy elements from into it:

http://docs.oracle.com/javase/6/docs/api/java/util/Vector.html#addAll(java.util.Collection)

Afshin Moazami
  • 2,092
  • 5
  • 33
  • 55
AntonyM
  • 1,602
  • 12
  • 12
0

Try this,

vector.set(i, new Vector().addAll(copyedVector));
Adeel Ansari
  • 39,541
  • 12
  • 93
  • 133
0

Try this. Add data to vectors by yourself.

Vector<T> vector1 = new Vector<T>();
Vector<T> vector2 = new Vector<T>();

vector1.addAll(vector2);