本文介绍了Java - HashMap混淆了碰撞处理和get()方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我正在使用一个 HashMap ,并且我无法直接回答 get()方法适用于碰撞情况。 比方说 n> 1 对象被放置在相同的键中。它们存储在 LinkedList 中吗?它们是否被覆盖,以便只有放置在该键中的最后一个对象在那里存在?他们是否使用其他碰撞方法? 如果他们被放置在 LinkedList 中,有没有办法检索整个列表?如果没有,是否还有一些其他内置的 Java 地图,我可以在这里做到这一点? 为了我的目的,单独的链接将是理想的,好像有碰撞一样,我需要能够查看列表并获取关于其中所有对象的信息。在 Java 中执行此操作的最佳方式是什么? 感谢您的帮助! 解决方案是的,假设你正在把这个键放到那个键上(根据 Object.equals ,而不是 Object.hashCode 。)在多个值中指定 Map.put javadoc :如果你想将一个键映射到多个值,你可能会更好使用类似Guava的 ListMultimap , ArrayListMultimap ,它将键映射到值列表。 (披露:我对Guava有贡献)如果你不能容忍第三方库,那么你真的必须有一个 Map< Key,List< Value>> ,虽然这可能会有点笨拙。 I'm using a HashMap and I haven't been able to get a straight answer on how the get() method works in the case of collisions.Let's say n > 1 objects get placed in the same key. Are they stored in a LinkedList? Are they overwritten so that only the last object placed in that key exists there anymore? Are they using some other collision method?If they are placed in a LinkedList, is there a way to retrieve that entire list? If not, is there some other built in map for Java in which I can do this?For my purposes, separate chaining would be ideal, as if there are collisions, I need to be able to look through the list and get information about all the objects in it. What would be the best way to do this in Java? Thanks for all your help! 解决方案 Yes, assuming you're putting multiple values with the same key (according to Object.equals, not Object.hashCode.) That's specified in the Map.put javadoc:If you want to map a key to multiple values, you're probably better off using something like Guava's ListMultimap, ArrayListMultimap in specific, which maps keys to lists of values. (Disclosure: I contribute to Guava.) If you can't tolerate a third-party library, then really you have to have a Map<Key, List<Value>>, though that can get a bit unwieldy. 这篇关于Java - HashMap混淆了碰撞处理和get()方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
10-20 09:28