HashSet和Set之间有什么区别? [英] What's the difference between HashSet and Set?

查看:194
本文介绍了HashSet和Set之间有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

看到类似代码片段

Set<Record> instances = new HashSet<Record>();

我想知道Hashset是否是一种特殊的集合。它们之间有什么区别吗?

I am wondering if Hashset is a special kind of set. Any difference between them?

推荐答案

A 集合代表一个通用的集合价值观。 TreeSet 是一个元素排序(因而有序)的集合, HashSet 是一个元素集合是排序或订购。

A Set represents a generic "set of values". A TreeSet is a set where the elements are sorted (and thus ordered), a HashSet is a set where the elements are not sorted or ordered.

A HashSet 通常比a快很多 TreeSet

A HashSet is typically a lot faster than a TreeSet.

A TreeSet 通常实现为红黑树(见 http://en.wikipedia.org/wiki/Red-black_tree - 我没有验证sun / oracle的 TreeSet 的实际实现,而 HashSet 使用 Object.hashCode()在数组中创建索引。红黑树的访问时间为 O(log(n)),而 HashSet 的访问时间范围为恒定时间到最坏的情况(每个项目都有相同的hashCode),你可以在线性搜索时间 O(n)

A TreeSet is typically implemented as a red-black tree (See http://en.wikipedia.org/wiki/Red-black_tree - I've not validated the actual implementation of sun/oracle's TreeSet), whereas a HashSet uses Object.hashCode() to create an index in an array. Access time for a red-black tree is O(log(n)) whereas access time for a HashSet ranges from constant-time to the worst case (every item has the same hashCode) where you can have a linear search time O(n).

这篇关于HashSet和Set之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆