在 java 映射中搜索对象

发布于 2024-12-18 18:38:54 字数 313 浏览 3 评论 0原文

我是 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 技术交流群。

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

发布评论

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

评论(3

对风讲故事 2024-12-25 18:38:54

Map 及其实现中涉及比较的所有方法都使用对象的“equals”方法。如果您尝试将键+值添加到已经包含与它比较的键的条目的Map,则新的键+值将替换旧的键+值。

请参阅文档

例如, containsKey(Object key) 方法的规范规定:“当且仅当此映射包含键 k 的映射且满足 (key==null ? k==null : key.equals) 时,才返回 true (k))。”

如果实现可以通过其他方式(例如比较哈希码)确定键“不相等”,则它可能不会执行任何等于比较。

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:

For example, the specification for the containsKey(Object key) method says: "returns true if and only if this map contains a mapping for a key k such that (key==null ? k==null : key.equals(k))."

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.

不喜欢何必死缠烂打 2024-12-25 18:38:54

在您的示例中,您将执行

 TreeMap<MyObject, Integer> tree = ...
 Integer i = tree.get(x);

get(x) 将迭代您的 keys() 并返回与 aKey.equals(x )

In your example, you would do

 TreeMap<MyObject, Integer> tree = ...
 Integer i = tree.get(x);

The get(x) will iterate over your keys() and returning the integer value for the key matching aKey.equals(x).

北笙凉宸 2024-12-25 18:38:54

在大多数情况下,Map 由哈希表支持,并且与 HashMap 非常相似。 TreeMap 通过在树上上下移动指针来提供每个节点的更多信息,但查找仍然通过哈希完成(我相信)

In most cases, Maps are backed by a hash table, and are very similar to a HashMap. 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)

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