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

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

    About your first question...

    List, Map and Set serve different purposes. I suggest reading about the Java Collections Framework at http://java.sun.com/docs/books/tutorial/collections/interfaces/index.html.

    To be a bit more concrete:

    • use List if you need an array-like data structure and you need to iterate over the elements
    • use Map if you need something like a dictionary
    • use a Set if you only need to decide if something belongs to the set or not.

    About your second question...

    The main difference between Vector and ArrayList is that the former is synchronized, the latter is not synchronized. You can read more about synchronization in Java Concurrency in Practice.

    The difference between Hashtable (note that the T is not a capital letter) and HashMap is similiar, the former is synchronized, the latter is not synchronized.

    I would say that there are no rule of thumb for preferring one implementation or another, it really depends on your needs.

提交回复
热议问题