在 Java 中维护一组不同的对象

发布于 2024-11-01 06:54:16 字数 433 浏览 7 评论 0原文

我正在尝试在内存非常有限的环境中实现地图。我希望映射的值类型有许多重复项(即不仅有许多 x 和 y 使得 x.equals(y),而且有许多 x 和 y 使得 x == y)。因此,我想将这些指针保存在一个小数组中(在常见情况下,少于几十个条目),并使用从字节数组中膨胀的整数对其进行索引;通常这会节省大量成本。

不过,这需要某种方法来跟踪不同的引用。我可以在某个列表中跟踪它们,并在每次添加新值时对其进行线性搜索,但是地图不会缩放到超过数百个不同的值(并且,即使有很多不同的值)值不常见,但并非不可能)。这种映射对于内部 Java 类来说应该很容易实现,因为它只需要进行指针比较,但是这个接口似乎没有公开(事实上,因为默认的 Object hashCode 方法只是返回底层的指针)大多数实现中,我处于一个讽刺的位置,作为一个 Map 实现者,被实现 hashCode 的用户伤害了)。

有什么办法可以得到这种行为吗?

I'm trying to implement a Map in a very memory restricted environment. The value type of the map I expect to have many duplicates (i.e. not just that there are many x and y such that x.equals(y), but many x and y such that x == y). Therefore, I'd like to keep these pointers in a small array (in the common case, less than a few dozen entries), and index into it using an integer which gets inflated out of a byte array; usually this will result in a substantial savings.

This requires though some way of keeping track of the distinct references, though. I could just keep track of them all in some list, and linear-search through it every time a new value is added, but then the map won't scale to more than a few hundred distinct values (and, even though lots of distinct values is uncommon, it's not impossible). This kind of map should be easy for an internal Java class to implement, since it just needs to do pointer comparisons, but this interface doesn't seem to be exposed (in fact, since the default Object hashCode method just returns the underlying pointer in most implementations, I'm in the ironic position of being a Map implementer hurt by users implementing hashCode).

Is there any way to get this sort of behavior?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

棒棒糖 2024-11-08 06:54:16

您是否正在寻找 java.lang.System.identityHashCode(Object)== 运算符?

Are you looking for java.lang.System.identityHashCode(Object) and == operator?

儭儭莪哋寶赑 2024-11-08 06:54:16

作为替代方案,您可以考虑以下方法:

如果您有一个地图,其中有很多重复值(其中 entry1.getValue() == entry2.getValue() ),那么您可以使用您的当前值作为键,当前键作为项目列表指向内存中的同一对象。

Map<SomeType1, List<SomeType2> map = new IdentityHashMap<SomeType1, List<SIneType2>>();

As an alternative you may consider the following:

If you have a map where you have a lot of dublicate values (where entry1.getValue() == entry2.getValue() ), then you may use your current values as a key, and the current keys that point to the same object in memory as a list of items.

Map<SomeType1, List<SomeType2> map = new IdentityHashMap<SomeType1, List<SIneType2>>();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文