ExerciseDifficulty: Advanced1 min

Practice: Naming the Set or Queue for Five Requirements

Seen-before checks in three orders, the most urgent job, and an undo history.

Sets are chosen by the iteration order you need, and queues by which element should come out next. For each requirement below, name the collection and say what the requirement rules out, all five before you open the answer.

The five requirements
The requirement
1Record which customer references have been seen, and ask often
2The same, but the report must list them in the order they arrived
3The same, but the report must list them alphabetically
4Hold work items and always take the most urgent one next
5Undo history: the last action taken is the first one undone
The five answers, and what each requirement rules out
Each requirement, the collection, and what it rules out
UseWhat the requirement ruled out
1HashSetA list, because contains on one is a walk
2LinkedHashSetHashSet, whose iteration order is not promised
3TreeSetBoth hash sets; or sort a copy at the end, if adding is the frequent operation
4PriorityQueueArrayDeque, which has no notion of urgency
5ArrayDeque used as a stackStack, which is synchronised and exposes Vector

The third has two defensible answers, which is why it is here. A TreeSet keeps order on every add; sorting a HashSet once at the end does the work only once. Which wins depends on how many adds there are per report.