Rule of thumb for choosing an implementation of a Java Collection?

前端 未结 11 1512
执念已碎
执念已碎 2020-11-29 16:06

Anyone have a good rule of thumb for choosing between different implementations of Java Collection interfaces like List, Map, or Set?

For example, generally why or i

11条回答
  •  伪装坚强ぢ
    2020-11-29 16:43

    Theoretically there are useful Big-Oh tradeoffs, but in practice these almost never matter.

    In real-world benchmarks, ArrayList out-performs LinkedList even with big lists and with operations like "lots of insertions near the front." Academics ignore the fact that real algorithms have constant factors that can overwhelm the asymptotic curve. For example, linked-lists require an additional object allocation for every node, meaning slower to create a node and vastly worse memory-access characteristics.

    My rule is:

    1. Always start with ArrayList and HashSet and HashMap (i.e. not LinkedList or TreeMap).
    2. Type declarations should always be an interface (i.e. List, Set, Map) so if a profiler or code review proves otherwise you can change the implementation without breaking anything.

提交回复
热议问题