Card 03/ 08

ComparisonDifficulty: Intermediate1 min

List, Set and Queue on Order, Duplicates and Access

The three promises, laid out on the axes that actually separate them. Two of the rows decide almost every choice you will make.

The three interfaces on order, duplicates, access and removal
Compared onListSetQueue
Keeps insertion orderYesNot promisedYes, for the ends
Allows duplicatesYesNoYes
Reach an element by positionYes, get(i)NoNo
Which one comes outWhichever you ask forNo such questionDecided by the queue
Ask whether something is in itWalks the whole listOne hash lookupWalks it

The last row is the one people underuse. Asking a list whether it contains something means comparing against every element; asking a set means one hash and one bucket. A contains inside a loop over a list is the most common accidental loop-inside-a-loop in Java.

The decision rule. Need positions or duplicates, or the order they arrived in? List. Need to ask "have I seen this" often, or need each thing once? Set. Adding at one end and taking from the other? Queue.