List
A list has an order and does allow duplicate values*. The two most commonly used implementations are LinkedList and ArrayList, the former being used if you don't know upfront how much data will be added to the list later, the latter if you do know.
Set
A set has no order and does not allow duplicate values*. You usually use it in form of a HashSet. There is nothing comparable available in JavaScript.
Map
A map has no order and does not allow duplicate values*. HashMap is how you use it in most cases. Each value is assigned a key and can be effectively accessed using that. In JavaScript this behaves very similar to an object.
*when I talk about order and duplicate values, I'm talking about the most common implementations. Theoretically you could have each type of collection with any characteristics you want, based on its implementation.
How do you decide which one to use?
Given enough experience in hands-on programming you instinctively know which data structure to use for a certain task. Here's some rule of thumbs for quick reference:
- for a certain amount of data without duplicates, which you want to access effectively (e.g. use contains-method) use a Set
- for a certain amount of data without any further requirements (duplicates allowed, no specific performance requirements) use a List. As mentioned before, use ArrayList if you know the final size upfront, LinkedList otherwise.
- if you have to lookup data repeatedly (not iterate them one by one, but get a specific item) use a Map where you assign a key which is easily creatable and look up your data using that.
Here's a short code snippet which I hope makes it clear what I'm talking about:
I found that beginnersbook.com has a few nice examples for each of the aforementioned implementations. Check them out for more details on each of them.
No comments:
Post a Comment