开发者

Generally speaking, should I check if an element is in a set before inserting it?

I'm currently using Java so I'm more interested in knowing if it'd 开发者_Go百科be better to just insert it, in terms of efficiency. Though I'm also curious if it's a bad practice.


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:

Set<Integer> set = new HashSet<Integer>();
boolean newAdditionToSet = set.add(1); 
System.out.println(newAdditionToSet); // true
newAdditionToSet = set.add(1); 
System.out.println(newAdditionToSet); // false

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.


Not necessary. Set.add() will check for you.

It will also return true or false based on whether the element was added or not.


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 the contains call, because it needs to replace the value if it already exists. So calling contains 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 the add 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜