4

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.

4
  • 3
    FYI, use of Vector is mostly discouraged nowadays. You should probably prefer ArrayList. Commented Apr 7, 2013 at 14:48
  • See stackoverflow.com/questions/1116636/… Commented Apr 7, 2013 at 14:48
  • Define 'doesn't work'. Commented Apr 7, 2013 at 14:49
  • Er, here 'doesn't work' means my eclipse marks my code as an error. Commented Apr 8, 2013 at 6:21

3 Answers 3

19

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Provided that array is a String.
Or better yet List<String> list = new Vector<String>(Arrays.asList(array));, or even better yet List<String> list = new ArrayList<String>(Arrays.asList(array));
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));

Comments

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);
}

1 Comment

I was trying to avoid doing it one by one, thanks anyway:)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.