HashMap(key:String,value:ArrayList)返回一个Object而不是ArrayList? [英] HashMap(key: String, value: ArrayList) returns an Object instead of ArrayList?

查看:468
本文介绍了HashMap(key:String,value:ArrayList)返回一个Object而不是ArrayList?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用(key:String,value:ArrayList)将数据存储在HashMap中。我遇到问题的部分声明一个新的ArrayListcurrent,在HashMap中搜索StringdictCode,如果找到则将current设置为返回值ArrayList。

I'm storing data in a HashMap with (key: String, value: ArrayList). The part I'm having trouble with declares a new ArrayList "current," searches the HashMap for the String "dictCode," and if found sets current as the returned value ArrayList.

ArrayList current = new ArrayList();      
if(dictMap.containsKey(dictCode)) {
    current = dictMap.get(dictCode);   
}

current = ...行返回编译错误:

The "current =..." line returns a compiler error of:

Error: incompatible types
found   : java.lang.Object
required: java.util.ArrayList

我不明白这个... HashMap是否返回一个Object而不是我存储的ArrayList它作为价值?如何将此对象转换为ArrayList?

I don't understand this... does that HashMap return an Object instead of the ArrayList I stored in it as the value? How do I convert this object into an ArrayList?

谢谢。

推荐答案

HashMap声明如何在该范围内表达?它应该是:

How is the HashMap declaration expressed in that scope? It should be:

HashMap<String, ArrayList> dictMap

如果不是,则假定为对象。

If not, it is assumed to be Objects.

例如,如果你的代码是:

For instance, if your code is:

HashMap dictMap = new HashMap<String, ArrayList>();
...
ArrayList current = dictMap.get(dictCode);

不起作用。相反,你想要:

that will not work. Instead you want:

HashMap<String, ArrayList> dictMap = new HashMap<String, Arraylist>();
...
ArrayList current = dictMap.get(dictCode);

泛型的工作方式是类型信息可供编译器使用,但在运行时不可用。这称为类型擦除。 HashMap(或任何其他泛型实现)的实现正在处理Object。类型信息用于在编译期间进行类型安全检查。请参阅泛型文档

The way generics work is that the type information is available to the compiler, but is not available at runtime. This is called type erasure. The implementation of HashMap (or any other generics implementation) is dealing with Object. The type information is there for type safety checks during compile time. See the Generics documentation.

另请注意 ArrayList 也作为泛型类实现,因此您可能还想在其中指定类型。假设您的 ArrayList 包含您的类 MyClass ,上面的行可能是:

Also note that ArrayList is also implemented as a generic class, and thus you might want to specify a type there as well. Assuming your ArrayList contains your class MyClass, the line above might be:

HashMap<String, ArrayList<MyClass>> dictMap

这篇关于HashMap(key:String,value:ArrayList)返回一个Object而不是ArrayList?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆