Card 02/ 08
All 8 cards
ExampleDifficulty: Intermediate1 min
The Same Ten Orders Held Three Ways
Ten order references, three of which are the same order added twice, put into each of the three shapes.
List<String> asList = new ArrayList<>();
Set<String> asSet = new HashSet<>();
Queue<String> asQueue = new ArrayDeque<>();
for (String ref : List.of("C", "A", "B", "A")) {
asList.add(ref);
asSet.add(ref);
asQueue.add(ref);
}
System.out.println(asList);
System.out.println(asSet.size());
System.out.println(asQueue.poll());[C, A, B, A]
3
CThe list kept all four, in the order they arrived. The set kept three, because the second "A" was already there. The queue handed back "C" first, because an ArrayDeque used as a queue gives things back in the order they went in.
What to notice: nothing was lost by accident. Each collection did what its interface promises, and the set discarding a duplicate is the reason you would choose a set at all.