EMZETT.
Login

Collections

In short: A collection of ready-made, reusable data structures (lists, sets, mappings) that a language ships as its standard library, instead of every program having to reimplement them itself.

In more detail: Collections typically include dynamically growing lists (e.g. ArrayList, LinkedList), unique sets (HashSet, TreeSet), and key-value mappings (maps, e.g. LinkedHashMap). Via a shared interface (see Iterator), all these structures can be iterated in a similar way, independent of their concrete internal implementation.

In Depth

The basic idea behind a collections framework: almost every program needs lists, unique sets, and key-value mappings — instead of every codebase reimplementing that over and over again (with varying quality and bugs), a language’s standard library provides well-tested, performant reference implementations.

The three main categories at a glance:

List    - ordered, duplicates allowed, access by index       -> [10, 20, 20, 30]
Set     - unordered OR sorted, NO duplicates                  -> {10, 20, 30}
Map     - key -> value mapping, keys unique                   -> {"a": 1, "b": 2}

Within each category, there are usually several concrete implementations with different strengths — for lists, for example, the choice between ArrayList (fast random access by index, but slow insertion in the middle) and LinkedList (fast insertion/deletion, but slow access by index). Which implementation is the right one depends on which operation occurs most frequently in the specific use case — see the individual articles for the exact trade-offs.

The decisive advantage of a unified collections framework is interchangeability: because all collection types implement the same basic interface (with methods like “add”, “remove”, “iterate”), code written against this interface can work with any concrete implementation with no changes:

function printAll(Collection collection):
    for each element in collection:
        print(element)
// works identically, no matter whether "collection" is an ArrayList, a HashSet, or something else

This allows the concrete implementation to be swapped out later (e.g. switching from a simple list to a more performant structure), without having to adjust code that only reads the collection — a direct example of the principle of abstraction.

See also: Data Structures, List, Set, Iterator