Imagine that I need to create a Collection of elements, where order could or could not matter. Effectively all I plan on doing is using the iterator. I notice most of my colleagues using an ArrayList vs LinkedHashSet/HashSet. My question is, if I know that these elements should be unique, should I be using a Set or a List? Effectively it doesn't really make a difference, but doesn't Set more effectively convey that the elements are unique?
I find this to be an interesting question for large enterprise applications for a few reasons: 1) If you can't guarantee the quality of code overall, using a Set can be dangerous. Why? Because equals() & hashcode might be incorrectly overridden and thus using a Set could cause some really nasty issues. 2) Using a List is more resilient to future changes. If duplicates for whatever reason become possible, no need for concern.
Essentially it boils down to: If I know I should expect unique elements, should I favor Set over List in all cases?
Edit: I suppose I'm also asking: Should Set be used to ensure that no duplicates are added, or can it also be used for the sole purpose of illustrating that no duplicates exist for ease of understanding?
1) is totally bogus. Don't work around bugs, fix them. Therefore, use any Set implementation if order doesn't matter, or SortedSet if order does matter. If elements don't have to be unique(and you should determine that now, and it usually should not ever change), feel free to use a List.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With