when to use Set vs. Collection?

后端 未结 8 1907
遥遥无期
遥遥无期 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

    Collection is also the supertype of List, Queue, Deque, and others, so it gives you more options. For example, I try to use Collection as a parameter to library methods that shouldn't explicitly depend on a certain type of collection.

    Generally, you should use the right tool for the job. If you don't want duplicates, use Set (or SortedSet if you want ordering, or LinkedHashSet if you want to maintain insertion order). If you want to allow duplicates, use List, and so on.

提交回复
热议问题