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

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

问题描述

我正在使用(键:字符串,值:ArrayList)将数据存储在 HashMap 中.我遇到问题的部分声明了一个新的 ArrayListcurrent",在 HashMap 中搜索字符串dictCode",如果找到,则将 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 返回一个对象而不是我作为值存储在其中的 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(或任何其他泛型实现)的实现正在处理对象.类型信息用于编译期间的类型安全检查.请参阅泛型文档.

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天全站免登陆