"Hi, Amigo. I'd like to tell you about collections today. In Java, a collection/container means a class whose main purpose is to store a collection of other elements. You already know one such class: ArrayList."
"In Java, collections are divided into three main groups: Set, List, Map."
"What is the difference between them?"
"Let me start with Set. Imagine many shoes thrown into a pile. This is a Set. You can add an element to a Set, search for it, or delete it. The important thing to note is that the set elements don't have a specific assigned order."
"That's not much to go on…"
"Now imagine the same pile of shoes arranged neatly along the wall. Now there is order. Each element has its own number. You could simply grab Pair No. 4 based on its number (index). This is a List. You can add an element to the beginning or the middle of a list, or remove an element – simply by using its index."
"I see. What about a Map?"
"Imagine the same shoes, but now each pair has a note with a name: 'Nick', 'Vic' or 'Anna'. This is a Map (also often called a dictionary). Each element has its own unique name which is used to address it. This unique name for each element is often called a 'key'. Thus, a Map is a set of key-value pairs. The key doesn't have to be a string: it can be any type. A Map whose keys are Integer is in fact a List (with some differences)."
"I more or less understand, but I'd like to see more examples."
"Rishi will give you examples, but I'd like to add a few words."
"Immediately after being created, collections and containers don't store anything, but you can add elements into them one by one. And if you do, their size will change dynamically."
"Now that's interesting. How do I know how many elements a collection contains?"
"You have the size() method for that. Collections have everything you might need. I believe that after a few more lessons you'll see for yourself just how convenient collections are."
"I hope so, Ellie."
GO TO FULL VERSION