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

前端 未结 11 1503
执念已碎
执念已碎 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:54

    Lists allow duplicate items, while Sets allow only one instance.

    I'll use a Map whenever I'll need to perform a lookup.

    For the specific implementations, there are order-preserving variations of Maps and Sets but largely it comes down to speed. I'll tend to use ArrayList for reasonably small Lists and HashSet for reasonably small sets, but there are many implementations (including any that you write yourself). HashMap is pretty common for Maps. Anything more than 'reasonably small' and you have to start worrying about memory so that'll be way more specific algorithmically.

    This page has lots of animated images along with sample code testing LinkedList vs. ArrayList if you're interested in hard numbers.

    EDIT: I hope the following links demonstrate how these things are really just items in a toolbox, you just have to think about what your needs are: See Commons-Collections versions of Map, List and Set.

提交回复
热议问题