简体   繁体   English

HashMap 的 get() 方法

[英]get() method of HashMap

I have a HashMap:我有一个哈希映射:

Map stuff = new HashMap<String, ArrayList<Thing>();

I am trying to use the .get() method to get the ArrayList , but I have an error message saying,我正在尝试使用.get()方法来获取ArrayList ,但我有一条错误消息说,

Object cannot be converted to ArrayList;对象无法转换为 ArrayList;

I'm not really sure why I am getting this error message?我不确定为什么会收到此错误消息? Also, is there another way to acquire the ArrayList at the key?另外,是否有另一种方法可以在键处获取ArrayList

Try parameterizing the Map declaration with <>.尝试使用 <> 参数化 Map 声明。

Map<String, ArrayList<Thing>> stuff = new HashMap<>() ;

Without the type declaration it will be an untyped Map, so the compiler will only be able to assume that the results of get are the most generic possible result, an Object.如果没有类型声明,它将是一个无类型的 Map,因此编译器只能假设 get 的结果是最通用的可能结果,一个对象。

With the diamond operator the compiler will infer the type of the right hand side from the left hand declaration.使用菱形运算符,编译器将从左侧声明推断右侧的类型。

You can cast the result of get back into an ArrayList, but it is better to parameterize the Map declaration instead.您可以将 get 的结果转换回 ArrayList,但最好改为参数化 Map 声明。 A cast will require runtime checks which have some performance cost and can potentially introduce crashes once your code becomes more difficult to understand.强制转换将需要运行时检查,这会带来一些性能成本,并且一旦您的代码变得更难以理解,可能会导致崩溃。 If you use the parameterized form instead, the compiler can prove that it is the right type, preventing crashes and running faster.如果改用参数化形式,编译器可以证明它是正确的类型,防止崩溃并运行得更快。

If you're using an old java from before java 1.7 you'll need to write out the full type in the <>.如果您使用的是 java 1.7 之前的旧 java,则需要在 <> 中写出完整类型。

See this tutorial from oracle for more information.有关更多信息,请参阅 oracle 的本 教程

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM