在 java 映射中搜索对象
我是 Java 新手,我正在使用 Map 类及其派生类。
我只是想知道如何在其中找到元素。仅执行指针/引用检查吗?
假设我有一个 TreeMap
。如果我有一个对象x
,我希望你搜索一个整数v
,使其键“等于”x
,即使它们是MyObject
类的 2 个独立实例,因此有 2 个不同的指针。
是否有任何方法(接口/超类的方法)可以执行此类操作?
提前致谢。
I am new to Java, I was working with Map class and its derivatives.
I was just wondering about how elements are found inside them. Is only a pointer/reference check performed?
Let's say I have a TreeMap<MyObject, Integer>
. If I have an object x
i would like you to search an integer v
such that its key is "equal" to x
even if they are 2 separate instances of the class MyObject
, hence 2 different pointers.
Is there any method (of an interface/superclass too) which can it do such operation?
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Map 及其实现中涉及比较的所有方法都使用对象的“equals”方法。如果您尝试将键+值添加到已经包含与它比较的键的条目的Map,则新的键+值将替换旧的键+值。
请参阅文档:
如果实现可以通过其他方式(例如比较哈希码)确定键“不相等”,则它可能不会执行任何等于比较。
All the methods that involve comparisons in Map and its implementations make use of the 'equals' method for the objects. If you attempt to add a key+value to a Map which already contains aentry with a key that would compare equals to it, then the new key+value replaces the old one.
See the documentation:
The implementation may not execute any equals comparison if it can determine that the keys are 'unequal' through some other means, such as comparing hashcodes.
在您的示例中,您将执行
get(x)
将迭代您的keys()
并返回与aKey.equals(x )
。In your example, you would do
The
get(x)
will iterate over yourkeys()
and returning the integer value for the key matchingaKey.equals(x)
.在大多数情况下,
Map
由哈希表支持,并且与HashMap
非常相似。 TreeMap 通过在树上上下移动指针来提供每个节点的更多信息,但查找仍然通过哈希完成(我相信)In most cases,
Map
s are backed by a hash table, and are very similar to aHashMap
.TreeMap
gives a bit more information with each node by having pointers up and down the tree, but lookups are still done via hashes (I believe)