Card 02/ 08
Collection Interfaces Example: The Same Orders Held Three Ways
Four order references, one repeated, and a list, a set and a queue each do something different with them.
Putting the same elements into a list, a set and a queue shows each interface's promise directly. Here four order references, with "A" repeated, go into all three:
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.
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.
← → move through sections and cards