Lists, sets, dictionaries
The three families of collections: the list (order, duplicates, index), the set (uniqueness) and the dictionary (key to value). Adding, accessing, removing, testing, and choosing the right collection for a need.
- 24 cards
- 5 topics
- Free
The outline, topic by topic
Each topic is weighted the way the exam weighs it.
- Concepts
- Questions
- Sort and link
- Scenarios
- Understand
A few cards from the deck
Collection: what is it?
Show the answer
An object that holds several elements and offers operations to add, find, remove and traverse them.
In Java,
List,SetandMapare the three basic interfaces: they describe what you can do, not how the elements are stored.ArrayList,HashSetorHashMapare classes that implement them.What are the three sizes printed?
```java
List<Integer> liste = new ArrayList<>();
Set<Integer> ensemble = new HashSet<>();
Map<String, Integer> dico = new HashMap<>();
for (int n : new int[] {3, 5, 3}) {
liste.add(n);
ensemble.add(n);
}
dico.put("a", 1);
dico.put("a", 2);
System.out.println(liste.size() + " " + ensemble.size() + " " + dico.size());`3 2 13 3 22 2 13 2 2
Show the answer
3 2 1The list keeps duplicates (3 elements), the set drops them (3 and 5), and the dictionary has a single entry for the key "a" whose value went from 1 to 2.
In a Java list, an element is read with get(i), where i is its …; the first element has index ….
Show the answer
In a Java list, an element is read with get(i), where i is its index; the first element has index 0.
An index outside the list, such as
get(3)on three elements, raisesIndexOutOfBoundsException: valid indices go from 0 to size - 1.List: what is it?
Show the answer
An ordered collection where each element has a position numbered from 0 and the same value may appear several times.
It keeps insertion order and accepts duplicates: after
add(3),add(5),add(3), aListholds[3, 5, 3]andget(0)returns 3.A shop must instantly find a product from its reference. Which structure should it use?
- A list of products, traversed until the reference is found
- A dictionary keyed by the reference
- A set of products, sorted by reference
- A list of references, the position standing for the product
Show the answer
A dictionary keyed by the reference
Finding data by an identifier is the dictionary's job:
products.get(ref). A list would force comparing everything, and a set attaches no data to a reference.