3

Do I have to push my elements one by one? I tried something like

String[] array;
array=...
Vector<String> vector = new Vector<String>(array);

but my eclipse marks this as an error.

Elderry
  • 1,902
  • 5
  • 31
  • 45

3 Answers3

18

Vector doesn't have a constructor that accepts an array directly.

Assuming that array is of type String[], you could do

Vector<String> vector = new Vector<String>(Arrays.asList(array));

Better to use ArrayList as it doesn't have the overhead of having synchronized methods. You could use

List<String> list = new ArrayList<>(Arrays.asList(array));

This will produce a mutable collection also.

Reimeus
  • 158,255
  • 15
  • 216
  • 276
4

That can't work, since, as the documentation shows, there is no Vector constructor taking an array as argument.

If you just want a non-modifiable list, use

List<String> list = Arrays.asList(array);

If you really want a Vector (but you should use ArrayList instead, because Vector is obsolete), use

Vector<String> vector = new Vector<String>(Arrays.asList(array));
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
0

I'm not 100% sure what you mean by 'one by one'. If you want to add an existing collection to a Vector, you could use this.

If you want to do it one by one, you need to iterate through the items, and call Vector's 'add' method.

for(String item: array) {
    vector.add(item);
}
Erik Pragt
  • 13,513
  • 11
  • 58
  • 64