221*_*21b 3 java vector hashmap
我有一个哈希图声明为:
HashMap<String, Double> hm = new HashMap<String, Double>();
Run Code Online (Sandbox Code Playgroud)
我将 Vector 声明为:
Vector<String> productList = new Vector<String>();
Run Code Online (Sandbox Code Playgroud)
现在,我尝试将键添加到向量中:
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.
Run Code Online (Sandbox Code Playgroud)
当我编译代码时,出现以下错误:
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)
Run Code Online (Sandbox Code Playgroud)
在尝试将值添加到向量之前,我们是否需要将其转换为 String 类型?我错过了什么吗?
Vector(Collection<? extends E)首先,您可以使用构造函数和调用Map.keySet()like在一行中完成此操作
Vector<String> productList = new Vector<>(hm.keySet());
Run Code Online (Sandbox Code Playgroud)
其次,你应该更喜欢1ArrayList
List<String> productList = new ArrayList<>(hm.keySet());
Run Code Online (Sandbox Code Playgroud)
1除非您与多个线程共享此列表,否则添加与 a 的同步Vector是有成本的。
| 归档时间: |
|
| 查看次数: |
8138 次 |
| 最近记录: |