Which one is faster? List.contains() or Map.containsKey()

后端 未结 4 1443
星月不相逢
星月不相逢 2021-01-31 17:34

I\'m writing an algorithm where I look for pairs of values which when added together results in another value I\'m looking for.

I figured out that using a Map

4条回答
  •  终归单人心
    2021-01-31 18:12

    I later realized that I don't really use the values contained in my Map so a List will suffice.

    Map isn't just a list of key-value pairs, it is a unique mapping from keys to values. So when you change from Map to List, you are allowing duplicates where you previously didn't. On the other hand, a Set is exactly a Map without the values. So consider using a HashSet.

    As for the search complexities:

    list.contains is O(n), hashSet.contains is O(1), and treeSet.contains is O(log n).

    For general information on now HashMap works, google for "hashtable". For TreeMap, google for "binary tree" or similar. Wikipedia has good entries on these subjects.

    Be careful, however, to avoid the class Hashtable. It's an archaeological artefact in the modern library. For your case HashSet is probably the best choice.

提交回复
热议问题