有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java使用ArrayList或Vector来检索枚举?

请参阅返回Enumeration<?>的两个不同实现

Vector<String> v = new Vector<>(map.keySet());
return v.elements();

List<String> v = new ArrayList<>(map.keySet());
return Collections.enumeration(v);

请注意,此处的返回类型Enumeration<?>无法更改

使用一个比另一个有什么好处吗

由于枚举类是同步的,我是否应该继续使用^{


我的目的不是比较Vector和ArrayList,而是从以上两种特定的代码用法中找到更好的实现。这里的答案也不同于What are the differences between ArrayList and Vector?

所以我认为这不符合复制品的条件


共 (4) 个答案

  1. # 1 楼答案

    我认为,如果你只想得到枚举,没有什么区别

    向量构造函数如下所示

    public Vector(Collection<? extends E> c) {
        elementData = c.toArray();
        elementCount = elementData.length;
        // c.toArray might (incorrectly) not return Object[] (see 6260652)
        if (elementData.getClass() != Object[].class)
            elementData = Arrays.copyOf(elementData, elementCount, Object[].class);
    }
    

    ArrayList构造函数如下所示

     public ArrayList(Collection<? extends E> c) {
        elementData = c.toArray();
        if ((size = elementData.length) != 0) {
            // c.toArray might (incorrectly) not return Object[] (see 6260652)
            if (elementData.getClass() != Object[].class)
                elementData = Arrays.copyOf(elementData, size, Object[].class);
        } else {
            // replace with empty array.
            this.elementData = EMPTY_ELEMENTDATA;
        }
    }
    
  2. # 2 楼答案

    使用这些过时的类(尽管不是弃用的)通常是一项业务决策。对此你无能为力,除非,如果可能的话,使用不同的API

    我不会用Vector。如果您自己的代码中不需要同步,请使用Collections框架。如果确实需要同步,请使用同步,使用java.util.concurrent中的类

    无论哪种方式,都可以使用Collections.enumeration将它们转换为枚举

  3. # 3 楼答案

    都不是。这两个你都不需要Collections.enumeration()接受Collection参数,SetCollection,而Map.keySet()返回Set

    你只需要:

    return Collections.enumeration(map.keySet());
    
  4. # 4 楼答案

    取决于你的用例,如果你不关心线程安全,就使用ArrayList,这样你就不会得到向量同步方法的额外开销, 否则使用向量