Java哈希表具有单独的链接冲突解决方案?

发布于 2024-08-31 06:05:25 字数 93 浏览 2 评论 0 原文

我已经使用内置的 java.util.hashtable 创建了一个程序,但现在我需要使用单独的链接来解决冲突。哈希表的这种实现是否可能?是否已经实现了使用单独链接的方法?

I have created a program using the built in java.util.hashtable but now I need to resolve collisions using separate chaining. Is it possible with this implementation of a hashtable? Is there one out there already implemented that uses separate chaining?

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

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

发布评论

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

评论(1

你没皮卡萌 2024-09-07 06:05:25

查看 Hashtable 实现的源代码 ,看起来它已经使用了单独的链接。如果您查看从第 901 行开始的 Entry 类,您会发现它引用了另一个名为 next 的 Entry。如果您随后查看 put() 方法,则在第 420 行,next 引用通过构造函数填充为之前存储在该存储桶中的任何元素。

请注意,您通常不应该关心诸如此类的实现细节。 Java 集合框架可能是 Java 中使用最广泛的框架之一,因此您应该假设作者已经将性能调整到了预期的水平。

我想指出的另一件事是 Hashtable 类已大部分被 HashMap 类(也使用单独的链接,请参阅 此处)。两者之间的主要区别在于,Hashtable 中的所有方法都是同步的,而在 HashMap 中则不是。在单线程环境中运行的情况下,这会带来更好的性能(可能是这个问题的原因?)。

如果您确实需要线程安全的映射实现,那么您应该考虑在对HashMap .com/javase/6/docs/api/java/util/Collections.html#synchronizedMap(java.util.Map)" rel="nofollow noreferrer">Collections.synchronizedMap(),或使用 ConcurrentHashMap< /代码>

Looking at the source of the Hashtable implementation, it looks like it already uses separate chaining. If you look at the Entry<K,V> class starting at line 901, you'll see that it has a reference to another Entry named next. If you then look at the put() method, on line 420 the next reference is populated via the constructor to be whatever element was previously stored in that bucket.

Note that you shouldn't generally be concerned about implementation details such as these. The Java Collections Framework is probably one of the most widely used frameworks in Java, and as such you should assume that the authors have tuned the performance to be as good as it's going to get.

One other thing I'd like to point out is that the Hashtable class has been mostly replaced by the HashMap class (which also uses separate chaining, see here). The main difference between the two is that all of the methods in Hashtable are synchronized, whereas in HashMap they are not. This leads to better performance in situations where you are running in a single threaded environment (possibly the reason for this question?).

If you do need a thread-safe map implementation, then you should consider either wrapping a normal HashMap in a call to Collections.synchronizedMap(), or using a ConcurrentHashMap.

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