when to use Set vs. Collection?

后端 未结 8 1925
遥遥无期
遥遥无期 2020-12-24 10:55

Is there any practical difference between a Set and Collection in Java, besides the fact that a Collection can include the same elemen

8条回答
  •  一个人的身影
    2020-12-24 11:24

    One other thing to consider... Sets have extra overhead in time, memory, and coding in order to guarantee that there are no duplicates. (Time and memory because sets are usually backed by a HashMap or a Tree, which adds overhead over a list or an array. Coding because you have to implement the hashCode() and equals() methods.)

    I usually use sets when I need a fast implementation of contains() and use Collection or List otherwise, even if the collection shouldn't have duplicates.

提交回复
热议问题