convert vector to list

后端 未结 2 1887
一整个雨季
一整个雨季 2021-02-05 04:26

How to convert a vector to a list?

2条回答
  •  盖世英雄少女心
    2021-02-05 04:45

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

提交回复
热议问题