一般来说,我应该在插入元素之前检查它是否在集合中吗?
我目前正在使用 Java,所以我更想知道就效率而言,直接插入它是否会更好。虽然我也很好奇这是否是一种不好的做法。
I'm currently using Java so I'm more interested in knowing if it'd be better to just insert it, in terms of efficiency. Though I'm also curious if it's a bad practice.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不需要。 API 会告诉您它是否已经存在(如果您需要知道),并且 Collections 代码非常高效 - 比您自己亲自检查更高效。
仅供参考,这是正在运行的 API:
这是“不好的做法”,因为 Set 无论如何也会检查它。您只需将新元素的工作负载加倍,同时保留现有元素的工作负载。
No need. The API tells you if it's already there (if you need to know), and the Collections code is very efficient - more efficient than taking the trouble to check it yourself.
FYI, here's the API in action:
It's "bad practice", because the Set will also be checking it anyway. You're just doubling to workload for new elements, while keeping the workload for existing elements.
一般来说,直接插入元素效率更高。对于正常的
Set
实现,插入代码几乎重复了contains
调用的工作,因为如果值已经存在,它需要替换该值。因此,首先调用contains
通常是浪费时间,并且通常是不好的做法。但并非总是如此!
您应该调用
contains
的一种情况是,如果您不希望使用add
调用来替换集合中的现有值。这种情况偶尔会出现;例如,如果您使用该集合来规范化一堆值。Generally speaking, it is more efficient to just insert the element. For a normal
Set
implementation, the insertion code pretty much duplicates the work of thecontains
call, because it needs to replace the value if it already exists. So callingcontains
first is generally a waste of time, and is generally bad practice.But not always!
One case where you should call
contains
is if you don't want theadd
call to replace an existing value in the set. This situation does arise occasionally; e.g. if you are using the set to canonicalize a bunch of values.没有必要。 Set.add() 会为你检查。
它还会根据元素是否已添加返回 true 或 false。
Not necessary. Set.add() will check for you.
It will also return true or false based on whether the element was added or not.