when to use Set vs. Collection?

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

    I think you already have it figured out- use a Set when you want to specifically exclude duplicates. Collection is generally the lowest common denominator, and it's useful to specify APIs that accept/return this, which leaves you room to change details later on if needed. However if the details of your application require unique entries, use Set to enforce this.

    Also worth considering is whether order is important to you; if it is, use List, or LinkedHashSet if you care about order and uniqueness.

提交回复
热议问题