集合和基于集合的操作有哪些优点?
我知道什么是集合以及集合的常见操作,例如并集、交集、差集、子集。但是我不明白在哪些情况下需要基于集合的操作?有现实世界的例子吗?与使用列表或哈希相比,使用集合有哪些优点?如果我有两个列表,那么我也可以找到这些列表的并集、交集。那么为什么要使用集合呢?
编辑 我特别想知道现实世界中我应该使用集合而不是列表的情况。
I know what Sets are and common operations on sets like union, intersection, difference, subset. However i don't understand in which situations are set based operations desired? Any real world examples? What are the advantages of using set vs using a list or a Hash? If i have two lists then i can find the union,intersection of those lists too. So why use Sets?
Edit
I specifically want to know real world situations where i should use a set instead of a list.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
除此之外,集合通常保证 O(logN) 的访问时间。它们还强制只使用一个给定值的条目(当您尝试添加重复项时抛出异常)。
哈希通常提供 O(1) 访问,但不保证唯一性。
Among other things, sets typically guarantee access times of O(logN). They also enforce only one entry with a given value (by throwing exceptions when you try to add a duplicate).
Hashes typically offer O(1) access, but do not guarantee uniqueness.
Set
保证其中没有重复的对象。List
则不然,因此您可以在列表中包含多个“相等”对象的条目。有数以百万计的东西你可以使用set,它会让你的生活变得更轻松,例如,一组国家,一组用户名等。如果你使用列表来存储这些数据,你将需要检查是否在添加新元素之前,您的列表已包含相同的元素或不包含相同的元素,除非列表允许有重复项。换句话说,集合可以被认为是一个没有任何重复项的列表。然而,Java 中 Set 和 List 的接口并不完全相同。例如,您无法获取集合中特定位置的元素。这是因为位置在集合中并不重要(但对于列表而言)。因此,选择使用哪个数据收集完全取决于目的。
我本人发现
Set
在许多情况下非常有用,并且减少了重复检查的数量。我的用例之一是使用 set 来查找分子中有多少化学元素。该分子包含原子对象列表,每个原子都与一个元素符号相关联,因此为了找到元素的类型,我循环遍历所有原子并将元素添加到元素集中。所有重复项都会被轻松删除。Set
guarantees there there is no duplicate object in it.List
doesn't so you can have multiple entries of "equal" objects in a list. There are million of things that you can use set and it will make your life much easier, for example, a set of countries, a set of username, etc. If you use a list to store these data, you will need to check whether your list has already contained the same element or not before adding the new one unless the list is allowed to have duplicates.In other words, set may be considered as a list without any duplicates. However, the interface of Set and List aren't really the same in Java. For example, you aren't able to get the element at certain position in a set. This is because position is not important in the set (but it is for a list). Therefore, selecting which data collection to use depends entirely on the purpose.
I, myself, found that
Set
is very useful in many cases and reduces the amount of checking for duplicates. One of my use cases is to use set to find how many chemical elements are in a molecule. The molecule contains a list of atom objects and each atom is associated to a element symbol so in order to find the type of element, I loop over all the atoms and add the element to an element set. All the duplicates are removed without hassle.