包含集合中的方法替换 [英] Contains method replacement in collection
问题描述
我还能用什么代替collection的contains方法来查找集合中的类似条目.contains是一种非常繁琐(费时)的方法.
What else i can use instead of contains method of collection to find out the similar entry in the collection.As contains is a very heavy(time consuming) method to use.
现在我正在使用包含这样的
Right now i am using contains like this
if (EntityTree.setMobileEnablerTxnList.contains(iMobileEnablerTxnList)) {
}
setMobileEnablerTxnList是一个集合.
Here setMobileEnablerTxnList is a set.
推荐答案
包含
方法不一定非常繁琐(耗时).例如,如果您使用 HashSet
,则速度会很快.对于 HashSet
,它将计算对象的 hashCode
,并且仅遍历相应存储桶"中的对象.当然,它不会遍历所有元素(否则您将无法很好地实现 hashCode
方法).
The contains
method is not necessarily very heavy (time consuming). For example if you use a HashSet
it is rather fast. For a HashSet
it will calculate the hashCode
of the object, and only go over the objects in the corresponding 'bucket'. It will certainly not go over all elements (or you would have a very poor implementation of the hashCode
method).
这可以在 HashSet#contains
方法的源代码中看到,该方法最终在 HashMap
中调用以下代码:
This can be seen in the source code of the HashSet#contains
method, which ultimately calls the following code in HashMap
:
final Entry<K,V> getEntry(Object key) {
int hash = (key == null) ? 0 : hash(key.hashCode());
for (Entry<K,V> e = table[indexFor(hash, table.length)];
e != null;
e = e.next) {
Object k;
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
}
return null;
}
这清楚地表明它仅在有限的一组对象上循环.
This clearly shows it loops only over a limited set of objects.
另请参阅此问题,以获取有关 HashMap 的更多信息code>(由
HashSet
内部使用)
See also this question for more information about a HashMap
(which is used internally by a HashSet
)
最后一条建议:如果您遇到性能问题,请使用探查器查看实际瓶颈所在的位置.我怀疑会在 contains
调用中.
Last piece of advise: if you have performance problems, use a profiler to see where the actual bottleneck is located. I doubt it will be in the contains
call.
这篇关于包含集合中的方法替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!