将HashMap的键值对(String)转换为Vector <String>?

3

I have a hashmap declared as :

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

我正在声明一个向量:

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

现在,我正在尝试将键添加到向量中:
  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)

我们在尝试将值添加到向量之前,需要将其转换为字符串类型吗?我有什么遗漏的吗?

2
你可以使用Vector<String> productList = new Vector<String>(hm.keySet()); - αƞjiβ
2个回答

5

首先,您可以使用Vector(Collection<? extends E)构造函数和调用Map.keySet()来完成一行代码。

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

其次,您应该优先考虑使用 ArrayList1

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

1除非您将此列表与多个线程共享,否则使用Vector添加同步是一种成本。


谢谢,那个方法可行!只是好奇,当 hm.keySet() 返回键后,向量如何映射集合的值? - 221b
这里相当于将keySet中的所有元素添加到Collection中。 - Elliott Frisch
明白了!谢谢! :) - 221b

2

不要使用原始类型。

使用增强型for循环可以让您的代码更简洁:

  for(String key : hm.keySet()) {
     productList.add(key);
  }

或者

  for(Map.Entry<String,Double> entry : hm.entrySet()) {
     productList.add(entry.getKey());
  }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接