我什么时候应该使用 HashSet<T>类型? [英] When should I use the HashSet<T> type?
问题描述
我正在探索 HashSet
类型,但我不明白它在集合中的位置.
I am exploring the HashSet<T>
type, but I don't understand where it stands in collections.
可以用它来代替List
吗?我想象 HashSet
的性能会更好,但我看不到对其元素的单独访问.
Can one use it to replace a List<T>
? I imagine the performance of a HashSet<T>
to be better, but I couldn't see individual access to its elements.
仅用于枚举吗?
推荐答案
HashSet
的重要之处就在于它的名字:它是一个 set.对于单个集合,您唯一可以做的就是确定它的成员是什么,并检查一个项目是否是成员.
The important thing about HashSet<T>
is right there in the name: it's a set. The only things you can do with a single set is to establish what its members are, and to check whether an item is a member.
询问是否可以检索单个元素(例如 set[45]
)是对集合概念的误解.没有集合的第 45 个元素这样的东西.集合中的项目没有顺序.集合 {1, 2, 3} 和 {2, 3, 1} 在各方面都是相同的,因为它们具有相同的成员资格,而成员资格才是最重要的.
Asking if you can retrieve a single element (e.g. set[45]
) is misunderstanding the concept of the set. There's no such thing as the 45th element of a set. Items in a set have no ordering. The sets {1, 2, 3} and {2, 3, 1} are identical in every respect because they have the same membership, and membership is all that matters.
迭代 HashSet
有点危险,因为这样做会对集合中的项目强加一个顺序.该顺序并不是该集合的真正属性.你不应该依赖它.如果集合中项目的排序对您很重要,则该集合不是集合.
It's somewhat dangerous to iterate over a HashSet<T>
because doing so imposes an order on the items in the set. That order is not really a property of the set. You should not rely on it. If ordering of the items in a collection is important to you, that collection isn't a set.
集合真的很有限,并且有独特的成员.另一方面,它们真的很快.
Sets are really limited and with unique members. On the other hand, they're really fast.
这篇关于我什么时候应该使用 HashSet<T>类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!