是否有一个IdentityHashMap实现可维护插入顺序? [英] Is there an IdentityHashMap implementation that maintains insert order?

查看:63
本文介绍了是否有一个IdentityHashMap实现可维护插入顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个HashMap(1)通过对象引用匹配键,并且(2)迭代时保持插入顺序

I need a HashMap that (1) matches keys by Object reference, and (2) maintains insertion order when iterating

这些功能分别在IdentityHashMap和LinkedHashMap中实现.

These functionalities are implemented in IdentityHashMap and LinkedHashMap separately.

有什么方法可以获取适合我需要的数据结构?Java标准或第三方库(例如Guava)中存在的一种,或者通过在LinkedHashMap上使用一些技巧来实现,以便它使用对象引用来匹配键?

Is there any way to get a data structure that suits my need? Either one that is present in Java standard OR 3rd party libraries (like Guava), OR by using some trick on LinkedHashMap maybe, so that it uses object reference for matching keys?

推荐答案

您可以使用Guava的

You can use Guava's Equivalence for this:

Equivalence<Object> equivalence = Equivalence.identity();
Map<Equivalence.Wrapper<Object>, Object> map = new LinkedHashMap<>();
map.put(equivalence.wrap(a), b);

这篇关于是否有一个IdentityHashMap实现可维护插入顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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