gpt4 book ai didi

java - 提供默认哈希和相等方法的语言有哪些优点/缺点?

转载 作者:行者123 更新时间:2023-11-30 03:22:14 26 4
gpt4 key购买 nike

Python 和 Java 等语言提供基于对象标识符的默认哈希和相等实现。这允许在基于哈希的数据结构(如集合)中使用任何新的类类型。

根据我的经验,这是一个陷阱。开发人员编写他们的对象,然后遇到奇怪的(但技术上正确的)行为,例如:

>>> len(set([Foo(5), Foo(5)]))
2

这种默认行为背后的理由是什么?基于身份的哈希和相等何时有用?与仅仅抛出未实现的异常来强制程序员创建对该对象有意义的行为相比,这样做有什么好处?

最佳答案

显然,我们只能推测为什么这些方法是这样设计的。与许多语言一样,有时设计者希望他们可以回去改变他们设计某个功能的方式。

例如,有些人会争辩说,如果 Java 从头开始​​重新设计,也许会出现类似 checked exceptions 的情况。不会被包括在内。或者,Object 类可能不包含 waitnotify 方法等。那么,至少在涉及 Object 时,有可能吗? hashCode() 方法,如果今天从头开始重新设计 Java,该功能的设计会有所不同?

说到equals方法。我认为每个对象都拥有它并且其默认实现执行引用相等是非常有意义的。

至于 hashCode 方法,那么我必须同意 OP 的观点,很多时候,使用起来很尴尬。有时,有些对象我们永远不想在哈希表中使用,但我们想重新定义相等的逻辑。因此,要么您重新定义 hashCode (浪费精力),只是为了确保以后不会有人意外地在哈希表中不正确地使用它,或者您不这样做,然后您会遇到令人讨厌的意外当有人决定将对象放入哈希表时,这条路。

我个人发现了这个article由 C# 编译器团队的开发人员 Eric Lippert 撰写,非常有启发性,而且讨论也非常适用于 Java。他特别说了以下内容(最后一段很有趣):

What is GetHashCode used for?

It is by design useful for only one thing: putting an object in a hash table. Hence the name.

Why do we have this method on Object in the first place?

It makes perfect sense that every object in the type system should provide a GetType method; data's ability to describe itself is a key feature of the CLR type system. And it makes sense that every object should have a ToString, so that it is able to print out a representation of itself as a string, for debugging purposes. It seems plausible that objects should be able to compare themselves to other objects for equality. But why should it be the case that every object should be able to hash itself for insertion into a hash table? Seems like an odd thing to require every object to be able to do.

I think if we were redesigning the type system from scratch today, hashing might be done differently, perhaps with an IHashable interface. But when the CLR type system was designed there were no generic types and therefore a general-purpose hash table needed to be able to store any object.

关于java - 提供默认哈希和相等方法的语言有哪些优点/缺点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31075769/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com