Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert vector to list

Tags:

java

list

vector

How to convert a vector to a list?

like image 383
sarah Avatar asked Dec 29 '09 09:12

sarah


People also ask

How do I convert a vector to a List in R?

To convert Vector to List in R programming, use the as. list() function and pass the vector as a parameter, and it returns the list. The as. list() function convert objects to lists.

Can I convert set object to List object?

We can convert the set to list by using List. copyOf(object) in java. For this, we have to import the package java. util.


2 Answers

Vector is a concrete class that implements the List interface so technically it is already a List. You can do this:

List list = new Vector(); 

or:

List<String> list = new Vector<String>(); 

(assuming a Vector of Strings).

If however you want to convert it to an ArrayList, which is the closest List implementation to a `Vector~ in the Java Collections Framework then just do this:

List newList = new ArrayList(vector); 

or for a generic version, assuming a Vector of Strings:

List<String> newList = new ArrayList<String>(vector); 
like image 109
cletus Avatar answered Oct 10 '22 01:10

cletus


If you want a utility method that converts an generic Vector type to an appropriate ArrayList, you could use the following:

public static <T> ArrayList<T> toList(Vector<T> source) {     return new ArrayList<T>(source); } 

In your code, you would use the utility method as follows:

public void myCode() {     List<String> items = toList(someVector);     System.out.println("items => " + items); } 

You can also use the built-in java.util.Collections.list(Enumeration) as follows:

public void myMethod() {     Vector<String> stringVector = new Vector<String>();     List<String> theList = Collections.list(stringVector.elements());     System.out.println("theList => " + theList); } 

But like someone mentioned below, a Vector is-a List! So why would you need to do this? Perhaps you don't want some code you use to know it's working with a Vector - perhaps it is inappropriately down-casting and you wish to eliminate this code-smell. You could then use

// the method i give my Vector to can't cast it to Vector methodThatUsesList( Collections.unmodifiableList(theVector) ); 

if the List should be modified. An off-the-cuff mutable wrapper is:

public static <T> List<T> asList(final List<T> vector) {     return new AbstractList<T>() {         public E get(int index) { return vector.get(index); }         public int size() { return vector.size(); }         public E set(int index, E element) { return vector.set(index, element); }         public void add(int index, E element) { vector.add(index, element); }         public E remove(int index) { return vector.remove(index); }     } } 
like image 21
les2 Avatar answered Oct 10 '22 02:10

les2