我将数据存储在HashMap中(key:String,value:ArrayList).我遇到问题的部分声明一个新的ArrayList"current",在HashMap中搜索String"dictCode",如果找到则将current设置为返回值ArrayList.
ArrayList current = new ArrayList();
if(dictMap.containsKey(dictCode)) {
current = dictMap.get(dictCode);
}
Run Code Online (Sandbox Code Playgroud)
"current = ..."行返回编译器错误:
Error: incompatible types
found : java.lang.Object
required: java.util.ArrayList
Run Code Online (Sandbox Code Playgroud)
我不明白这个... HashMap是否返回一个Object而不是我存储在其中的ArrayList作为值?如何将此对象转换为ArrayList?
谢谢.
Jar*_*aus 36
HashMap声明如何在该范围内表达?它应该是:
HashMap<String, ArrayList> dictMap
Run Code Online (Sandbox Code Playgroud)
如果不是,则假定为对象.
例如,如果您的代码是:
HashMap dictMap = new HashMap<String, ArrayList>();
...
ArrayList current = dictMap.get(dictCode);
Run Code Online (Sandbox Code Playgroud)
那样不行.相反,你想要:
HashMap<String, ArrayList> dictMap = new HashMap<String, Arraylist>();
...
ArrayList current = dictMap.get(dictCode);
Run Code Online (Sandbox Code Playgroud)
泛型的工作方式是类型信息可供编译器使用,但在运行时不可用.这称为类型擦除.HashMap(或任何其他泛型实现)的实现正在处理Object.类型信息用于在编译期间进行类型安全检查.请参阅泛型文档.
另请注意,ArrayList它也是作为泛型类实现的,因此您可能还想在其中指定类型.假设您ArrayList包含您的班级MyClass,上面的行可能是:
HashMap<String, ArrayList<MyClass>> dictMap
Run Code Online (Sandbox Code Playgroud)
小智 11
public static void main(String arg[])
{
HashMap<String, ArrayList<String>> hashmap =
new HashMap<String, ArrayList<String>>();
ArrayList<String> arraylist = new ArrayList<String>();
arraylist.add("Hello");
arraylist.add("World.");
hashmap.put("my key", arraylist);
arraylist = hashmap.get("not inserted");
System.out.println(arraylist);
arraylist = hashmap.get("my key");
System.out.println(arraylist);
}
null
[Hello, World.]
Run Code Online (Sandbox Code Playgroud)
工作得很好......也许你在我的代码中发现了你的错误.
| 归档时间: |
|
| 查看次数: |
164739 次 |
| 最近记录: |