Hi All,
How to convert a vector to a list?
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 String
s).
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 String
s:
List<String> newList = new ArrayList<String>(vector);
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); }
}
}