检查List< String>的最快方法包含一个唯一的String [英] Fastest way to check if a List<String> contains a unique String
问题描述
基本上我有大约1,000,000个字符串,对于每个请求,我必须检查字符串是否属于列表。
Basically I have about 1,000,000 strings, for each request I have to check if a String belongs to the list or not.
我担心性能,那么最好的方法是什么? 的ArrayList
?哈希?
I'm worried about the performance, so what's the best method? ArrayList
? Hash?
推荐答案
最好的办法是使用 HashSet
并检查集合中是否存在字符串包含()
方法。 HashSet是通过使用Object方法 hashCode()
和 equals()
来快速访问而构建的。 HashSet
的Javadoc状态:
Your best bet is to use a HashSet
and check if a string exists in the set via the contains()
method. HashSets are built for fast access via the use of Object methods hashCode()
and equals()
. The Javadoc for HashSet
states:
此类为基本提供恒定的时间性能操作(添加,删除,包含和大小),
This class offers constant time performance for the basic operations (add, remove, contains and size),
HashSet 将对象存储在散列桶中,也就是说 hashCode
方法返回的值将确定哪个桶是对象这样,通过 equals()
方法检查 HashSet
必须执行的等式数量是多少。减少到同一个散列桶中的其他对象。
HashSet stores objects in hash buckets which is to say that the value returned by the hashCode
method will determine which bucket an object is stored in. This way, the amount of equality checks the HashSet
has to perform via the equals()
method is reduced to just the other Objects in the same hash bucket.
要有效地使用HashSets和HashMaps,必须符合等于
和 hashCode
合同概述。在 java.lang.String
的情况下,已经实现了这些方法。
To use HashSets and HashMaps effectively, you must conform to the equals
and hashCode
contract outlined in the javadoc. In the case of java.lang.String
these methods have already been implemented to do this.
这篇关于检查List< String>的最快方法包含一个唯一的String的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!