How to convert a vector to a list?
If you want a utility method that converts an generic Vector type to an appropriate ArrayList, you could use the following:
public static ArrayList toList(Vector source) {
return new ArrayList(source);
}
In your code, you would use the utility method as follows:
public void myCode() {
List 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 stringVector = new Vector();
List 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 List asList(final List vector) {
return new AbstractList() {
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); }
}
}