Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize a vector with an array in Java? [duplicate]

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.

like image 784
Elderry Avatar asked Oct 16 '25 03:10

Elderry


2 Answers

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.

like image 50
Reimeus Avatar answered Oct 17 '25 18:10

Reimeus


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));
like image 40
JB Nizet Avatar answered Oct 17 '25 16:10

JB Nizet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!