Home > Mobile >  Difference between key and index in arrays
Difference between key and index in arrays

Time:05-04

I'm confused with the terms index, key , key-value pair & element with respect to arrays in TCL or say any other programming language in general.

I know that we use index for non-associative arrays and keys for associative arrays , but don't understand why.

Can anyone help me understand the exact meaning (difference between them) and usage of these terms.

Thanks

CodePudding user response:

An index is typically numeric (it's an integer, starting at zero and increasing to number of elements minus one). It identifies the element of interest by its ordinal position in the array.

A key is typically a string or object. It identifies an element in the array "by name."

An element is just an item in an array.

Keys are used for "associative arrays" because you are "associating" a key with a value. A key-value pair is simply an object that contains both a key and the value associated with that key.

(Advanced)

How you use keys and indices has performance implications. If an "associative array" is implemented with a hash table, its performance is O(1). If it's implemented with a binary tree, it is O(n log n)

Accessing an array by its index is always O(1) because finding the correct element is essentially an arithmetic problem. Finding an item in an array if you have neither an index nor a key is O(n).

CodePudding user response:

The terminology can be a little confusing. What Tcl calls an array is always an associative array (implemented as a hash table), even if the keys happen to be numeric. Tcl lists are more like other languages' arrays. You read the value at position n in list l with lindex l n, where n is numeric (but a few other forms, like end are supported). As Robert Harvey points out this is a constant-time operation.

  • Related