我有一个哈希图声明为:

HashMap<String, Double> hm = new HashMap<String, Double>();


我将Vector声明为:

 Vector<String> productList = new Vector<String>();


现在,我正在尝试将键添加到vector中:

  Set set = hm.entrySet();
  // Get an iterator
  Iterator i = set.iterator();
  // Display elements
  while(i.hasNext()) {
     Map.Entry me = (Map.Entry)i.next();
     //System.out.print(me.getKey() + ": ");
     productList.add(me.getKey());
     //System.out.println(me.getValue());
  }

//hm is the HashMap holding the keys and values.


当我编译代码时,出现以下错误:

ProductHandler.java:52: error: no suitable method found for add(Object)
     productList.add(me.getKey());
                ^
method Collection.add(String) is not applicable
  (argument mismatch; Object cannot be converted to String)


在尝试将值添加到向量之前,是否需要将值转换为String类型?我错过了什么吗?

最佳答案

首先,您可以使用Vector(Collection<? extends E)构造函数和对Map.keySet()的调用在一行中完成此操作

Vector<String> productList = new Vector<>(hm.keySet());


其次,您应该选择ArrayList 1

List<String> productList = new ArrayList<>(hm.keySet());


1除非您要与多个线程共享此列表,否则添加与Vector的同步是一项成本。

09-10 03:01
查看更多