Quick Index
What and Why


A bag contains unordered elements. It may contain duplicates.

🛍
A bag is useful when an algorithm calls for a structure where order is not important -- e.g. perhaps a problem needs a structure only for the purpose of determining if it "contains" matches.

🛍


Gotcha -- Not Random 🐞


The order of elements in a bag does not need to be random. It may, in fact, be ordered.

When we say "order is not important" we simply mean that the object user of a bag should not expect any certain order of elements. The actual order depends how it is implemented (hidden under the hood).

A coder may decide to implement it as ordered or unordered.

Fundamental Operations


A bag has the following core operations:

OperationNotes
addAdd element into bag
anyReturn any element (do not remove)
removeRemove (and return) a given element from bag
containsReturn true if the bag contains a given element


FIFO or LIFO?


FIFO and LIFO do not apply to a bag.

Traversal (Iteration)


All of the elements in a bag can be yes be traversed, but the order of traversal is undefined.

Also see the section above "Gotcha -- Not Random".

ADT


See the ADT here...

References




Navigation