Content deleted Content added
→Pike: copy editing, etc. |
m →F#: {{code}} |
||
(74 intermediate revisions by 25 users not shown) | |||
Line 1:
{{ProgLangCompare}}
{{TOC limit|3}}
This '''
==Language support==
Line 9 ⟶ 8:
The following is a comparison of [[associative array]]s (also "mapping", "hash", and "dictionary") in various programming languages.
===
[[
For example:
<syntaxhighlight lang="awk">
phonebook["Sally Smart"] = "555-9999"
phonebook["John Doe"] = "555-1212"
Line 30 ⟶ 29:
The user can search for elements in an associative array, and delete elements from the array.
The following shows how multi-dimensional associative arrays can be simulated in standard
<syntaxhighlight lang=awk>
Line 48 ⟶ 47:
There is no standard implementation of associative arrays in [[C (programming language)|C]], but a 3rd-party library, C Hash Table, with BSD license, is available.<ref>[https://web.archive.org/web/20071015024120/http://www.cl.cam.ac.uk/~cwc22/hashtable/ here], archived [https://web.archive.org/web/20040902160534/http://www.cl.cam.ac.uk/~cwc22/hashtable/ here], with the source code available [https://github.com/davidar/c-hashtable/ here]. [[POSIX]] 1003.1-2001 describes the functions <code>hcreate()</code>, <code>hdestroy()</code> and <code>hsearch()</code></ref>
Another 3rd-party library, uthash, also creates associative arrays from C structures. A structure represents a value, and one of the structure fields serves as the key.<ref>
Finally, the [[GLib]] library also supports associative arrays, along with many other advanced data types and is the recommended implementation of the GNU Project.<ref>{{cite web |title=Hash Tables |url=https://developer.gnome.org/glib/stable/glib-Hash-Tables.html |website=Gnome Developer |access-date=3 August 2020}}</ref>
Similar to [[GLib]], [[Apple Inc.|Apple]]'s cross-platform [[Core Foundation]] framework provides several basic data types. In particular, there are reference-counted CFDictionary and CFMutableDictionary.
Line 64 ⟶ 63:
* assigning to the backing property of the indexer, for which the indexer is [[syntactic sugar]] (not applicable to C#, see [[#F#|F#]] or [[#Visual Basic .NET|VB.NET]] examples).
<syntaxhighlight lang=
// Not allowed in C#.
//
</syntaxhighlight>
The dictionary can also be initialized during construction using a "collection initializer", which compiles to repeated calls to <code>Add</code>.
<syntaxhighlight lang=
var
{ "Sally Smart", "555-9999" },
{ "John Doe", "555-1212" },
Line 86 ⟶ 85:
Values are primarily retrieved using the indexer (which throws an exception if the key does not exist) and the <code>TryGetValue</code> method, which has an output parameter for the sought value and a Boolean return-value indicating whether the key was found.
<syntaxhighlight lang=
var sallyNumber =
</syntaxhighlight>
<syntaxhighlight lang=
var sallyNumber = (
</syntaxhighlight>
In this example, the <code>sallyNumber</code> value will now contain the string <code>"555-9999"</code>.
Line 98 ⟶ 97:
The following demonstrates enumeration using a [[foreach loop]]:
<syntaxhighlight lang=
// loop through the collection and display each entry.
foreach (KeyValuePair<string,string> kvp in
{
Console.WriteLine("Phone number for {0} is {1}", kvp.Key, kvp.Value);
Line 109 ⟶ 108:
[[C++]] has a form of associative array called [[map (C++)|<code>std::map</code>]] (see [[Standard Template Library#Containers]]). One could create a phone-book map with the following code in C++:
<syntaxhighlight lang=
#include <map>
#include <string>
Line 123 ⟶ 122:
Or less efficiently, as this creates temporary <code>std::string</code> values:
<syntaxhighlight lang=
#include <map>
#include <string>
Line 137 ⟶ 136:
With the extension of [[C++11#Initializer lists|initialization lists]] in C++11, entries can be added during a map's construction as shown below:
<syntaxhighlight lang=
#include <map>
#include <string>
Line 152 ⟶ 151:
You can iterate through the list with the following code (C++03):
<syntaxhighlight lang=
std::map<std::string, std::string>::iterator curr, end;
for(curr = phone_book.begin(), end = phone_book.end(); curr != end; ++curr)
Line 160 ⟶ 159:
The same task in C++11:
<syntaxhighlight lang=
for(const auto& curr : phone_book)
std::cout << curr.first << " = " << curr.second << std::endl;
Line 167 ⟶ 166:
Using the structured binding available in [[C++17]]:
<syntaxhighlight lang=
for (const auto& [name, number] : phone_book) {
std::cout << name << " = " << number << std::endl;
Line 175 ⟶ 174:
In C++, the <code>std::map</code> class is [[Generic programming#Templates in C.2B.2B|templated]] which allows the [[data type]]s of keys and values to be different for different <code>map</code> instances. For a given instance of the <code>map</code> class the keys must be of the same base type. The same must be true for all of the values. Although <code>std::map</code> is typically implemented using a [[self-balancing binary search tree]], C++11 defines a second map called <code>[[std::unordered_map]]</code>, which has the algorithmic characteristics of a hash table. This is a common vendor extension to the [[Standard Template Library]] (STL) as well, usually called <code>hash_map</code>, available from such implementations as SGI and STLPort.
===
Initializing an empty dictionary and adding items in [[Cobra (programming language)|Cobra]]:
{{sxhl|2=python|1=<nowiki/>
dic as Dictionary<of String, String> = Dictionary<of String, String>()
dic.add('Sally Smart', '555-9999')
dic.add('John Doe', '555-1212')
dic.add('J. Random Hacker', '553-1337')
assert dic['Sally Smart'] == '555-9999'
}}
Alternatively, a dictionary can be initialized with all items during construction:
{{sxhl|2=python|1=<nowiki/>
dic = {
'Sally Smart':'555-9999',
'John Doe':'555-1212',
'J. Random Hacker':'553-1337'
}
}}
The dictionary can be enumerated by a for-loop, but there is no guaranteed order:
{{sxhl|2=python|1=<nowiki/>
for key, val in dic
print "[key]'s phone number is [val]"
}}
===ColdFusion Markup Language===
A structure in [[ColdFusion Markup Language]] (CFML) is equivalent to an associative array:
<syntaxhighlight lang=CFS>
Line 189 ⟶ 212:
writeDump(phoneBook); // entire struct
</syntaxhighlight>
===D===
[[D programming language|D]] offers direct support for associative arrays in the core language; such arrays are implemented as a chaining hash table with binary trees.<ref>{{Cite web|title=Associative Arrays - D Programming Language|url=
<syntaxhighlight lang=
int main() {
string[ string ] phone_book;
Line 230:
Looping through all properties and associated values, and printing them, can be coded as follows:
<syntaxhighlight lang=
foreach (key, value; phone_book) {
writeln("Number for " ~ key ~ ": " ~ value );
Line 238:
A property can be removed as follows:
<syntaxhighlight lang=
phone_book.remove("Sally Smart");
</syntaxhighlight>
===Delphi===
[[
<syntaxhighlight lang=
uses
SysUtils,
Line 265:
</syntaxhighlight>
<syntaxhighlight lang=
procedure TForm1.Button1Click(Sender: TObject);
var
Line 293:
===Erlang===
[[Erlang (programming language)|Erlang]] offers many ways to represent mappings;
====Keylists====
Keylists are lists of [[tuple]]s, where the first element of each tuple is a key, and the second is a value. Functions for operating on keylists are provided in the <code>lists</code> module.
<syntaxhighlight lang=
PhoneBook = [{"Sally
{"John Doe", "555-1212"},
{"J. Random Hacker", "553-1337"}].
Line 305 ⟶ 306:
Accessing an element of the keylist can be done with the <code>lists:keyfind/3</code> function:
<syntaxhighlight lang=
{_, Phone} = lists:keyfind("Sally
io:format("Phone number: ~s~n", [Phone]).
</syntaxhighlight>
====Dictionaries====
Dictionaries are implemented in the <code>dict</code> module of the standard library. A new dictionary is created using the <code>dict:new/0</code> function and new key/value pairs are stored using the <code>dict:store/3</code> function:
<syntaxhighlight lang=
PhoneBook1 = dict:new(),
PhoneBook2 = dict:store("Sally Smith", "555-9999", Dict1),
Line 321 ⟶ 323:
Such a serial initialization would be more idiomatically represented in Erlang with the appropriate function:
<syntaxhighlight lang=
PhoneBook = dict:from_list([{"Sally Smith", "555-9999"},
{"John Doe", "555-1212"}, {"J. Random Hacker", "553-1337"}]).
</syntaxhighlight>
The dictionary can be accessed using the <code>dict:find/2</code> function:
<syntaxhighlight lang=
{ok, Phone} = dict:find("Sally Smith", PhoneBook),
io:format("Phone: ~s~n", [Phone]).
Line 334 ⟶ 337:
In both cases, any Erlang term can be used as the key. Variations include the <code>orddict</code> module, implementing ordered dictionaries, and <code>gb_trees</code>, implementing general balanced trees.
====Maps====
Maps were introduced in OTP 17.0,<ref>{{Cite web|title=Erlang -- maps|url=https://erlang.org/doc/man/maps.html|access-date=2021-03-07|website=erlang.org}}</ref> and combine the strengths of keylists and dictionaries. A map is defined using the syntax <code>#{ K1 => V1, ... Kn => Vn }</code>:
<syntaxhighlight lang="erlang">
PhoneBook = #{"Sally Smith" => "555-9999",
"John Doe" => "555-1212",
"J. Random Hacker" => "553-1337"}.
</syntaxhighlight>
Basic functions to interact with maps are available from the <code>maps</code> module. For example, the <code>maps:find/2</code> function returns the value associated with a key:
<syntaxhighlight lang="erlang">
{ok, Phone} = maps:find("Sally Smith", PhoneBook),
io:format("Phone: ~s~n", [Phone]).
</syntaxhighlight>
Unlike dictionaries, maps can be pattern matched upon:
<syntaxhighlight lang="erlang">
#{"Sally Smith", Phone} = PhoneBook,
io:format("Phone: ~s~n", [Phone]).
</syntaxhighlight>
Erlang also provides syntax sugar for functional updates—creating a new map based on an existing one, but with modified values or additional keys:
<syntaxhighlight lang="erlang">
PhoneBook2 = PhoneBook#{
% the `:=` operator updates the value associated with an existing key
"J. Random Hacker" := "355-7331",
% the `=>` operator adds a new key-value pair, potentially replacing an existing one
"Alice Wonderland" => "555-1865"
}
</syntaxhighlight>
===F#===
===={{code|Map<'Key,'Value>}}====
At runtime, [[F Sharp (programming language)|F#]] provides the <code>Collections.Map<'Key,'Value></code> type, which is an immutable [[AVL tree]].
Line 343 ⟶ 381:
The following example calls the <code>Map</code> constructor, which operates on a list (a semicolon delimited sequence of elements enclosed in square brackets) of tuples (which in F# are comma-delimited sequences of elements).
<syntaxhighlight lang="fsharp">
let numbers =
[
Line 353 ⟶ 391:
=====Access by key=====
Values can be looked up via one of the <code>Map</code> members, such as its indexer or <code>Item</code> property (which throw an [[Exception handling|exception]] if the key does not exist) or the <code>TryFind</code> function, which returns an [[option type]] with a value of
<syntaxhighlight lang="fsharp">
let sallyNumber = numbers.["Sally Smart"]
// or
Line 369 ⟶ 407:
In both examples above, the <code>sallyNumber</code> value would contain the string <code>"555-9999"</code>.
===={{code|Dictionary<'TKey,'TValue>}}====
Because F# is a .NET language, it also has access to features of the [[.NET Framework]], including the
=====Creation=====
The <code>dict</code> function provides a means of conveniently creating a .NET dictionary that is not intended to be mutated; it accepts a sequence of tuples and returns an immutable object that implements
<syntaxhighlight lang="fsharp">
let numbers =
[
Line 384 ⟶ 422:
</syntaxhighlight>
When a mutable dictionary is needed, the constructor of
<syntaxhighlight lang="fsharp">
let numbers = System.Collections.Generic.Dictionary<string, string>()
numbers.Add("Sally Smart", "555-9999")
Line 396 ⟶ 434:
<code>IDictionary</code> instances have an indexer that is used in the same way as <code>Map</code>, although the equivalent to <code>TryFind</code> is <code>TryGetValue</code>, which has an output parameter for the sought value and a Boolean return value indicating whether the key was found.
<syntaxhighlight lang="fsharp">
let sallyNumber =
let mutable result = ""
Line 403 ⟶ 441:
F# also allows the function to be called as if it had no output parameter and instead returned a tuple containing its regular return value and the value assigned to the output parameter:
<syntaxhighlight lang="fsharp">
let sallyNumber =
match numbers.TryGetValue("Sally Smart") with
Line 421 ⟶ 459:
[[Visual FoxPro]] implements mapping with the Collection Class.
<syntaxhighlight lang="
mapping = NEWOBJECT("Collection")
mapping.Add("Daffodils", "flower2") && Add(object, key) – key must be character
Line 434 ⟶ 472:
[[Go (programming language)|Go]] has built-in, language-level support for associative arrays, called "maps". A map's key type may only be a boolean, numeric, string, array, struct, pointer, interface, or channel type.
A map type is written: <
Adding elements one at a time:
<syntaxhighlight lang=
phone_book := make(map[string] string) // make an empty map
phone_book["Sally Smart"] = "555-9999"
Line 447 ⟶ 485:
A map literal:
<syntaxhighlight lang=
phone_book := map[string] string {
"Sally Smart": "555-9999",
Line 457 ⟶ 495:
Iterating through a map:
<syntaxhighlight lang=
// over both keys and values
for key, value := range phone_book {
Line 470 ⟶ 508:
===Haskell===
The [[
<syntaxhighlight lang="
m = [("Sally Smart", "555-9999"), ("John Doe", "555-1212"), ("J. Random Hacker", "553-1337")]
Line 482 ⟶ 520:
Note that the lookup function returns a "Maybe" value, which is "Nothing" if not found, or "Just 'result{{' "}} when found.
The [[Glasgow Haskell Compiler
One is polymorphic functional maps (represented as immutable balanced binary trees):
<syntaxhighlight lang="
import qualified Data.Map as M
Line 515 ⟶ 553:
Just "555-1212"
Lists of pairs and functional maps both provide a purely functional interface, which is more idiomatic in Haskell. In contrast, hash tables provide an imperative interface in the [[
===Java===
In [[Java (programming language)|Java]] associative arrays are implemented as "maps", which are part of the [[Java collections framework]]. Since [[Java Platform, Standard Edition|J2SE]] 5.0 and the introduction of [[generic programming|generics]] into Java, collections can have a type specified; for example, an associative array that maps strings to strings might be specified as follows:
<syntaxhighlight lang=
Map<String, String> phoneBook = new HashMap<String, String>();
phoneBook.put("Sally Smart", "555-9999");
Line 529 ⟶ 567:
The {{Javadoc:SE|java/util|Map|get(java.lang.Object)|name=get}} method is used to access a key; for example, the value of the expression <code>phoneBook.get("Sally Smart")</code> is <code>"555-9999"</code>. This code uses a hash map to store the associative array, by calling the constructor of the {{Javadoc:SE|java/util|HashMap}} class. However, since the code only uses methods common to the interface {{Javadoc:SE|java/util|Map}}, a self-balancing binary tree could be used by calling the constructor of the {{Javadoc:SE|java/util|TreeMap}} class (which implements the subinterface {{Javadoc:SE|java/util|SortedMap}}), without changing the definition of the <code>phoneBook</code> variable, or the rest of the code, or using other underlying data structures that implement the <code>Map</code> interface.
The hash function in Java, used by HashMap and HashSet, is provided by the {{Javadoc:SE|java/lang|Object|hashCode()}} method. Since every class in Java [[Inheritance (
The <code>Object</code> class also contains the {{Javadoc:SE|name=equals(Object)|java/lang|Object|equals(java.lang.Object)}} method, which tests an object for equality with another object. Hashed data structures in Java rely on objects maintaining the following contract between their <code>hashCode()</code> and <code>equals()</code> methods:
Line 535 ⟶ 573:
For two objects ''a'' and ''b'',
<syntaxhighlight lang=
a.equals(b) == b.equals(a)
if a.equals(b), then a.hashCode() == b.hashCode()
Line 551 ⟶ 589:
====Map and WeakMap====
Modern JavaScript handles associative arrays, using the <code>Map</code> and <code>WeakMap</code> classes. A map does not contain any keys by default
=====Creation=====
A map can be initialized with all items during construction:
<syntaxhighlight lang=
["Sally Smart", "555-9999"],
["John Doe", "555-1212"],
["J. Random Hacker", "553-1337"],
]);
</syntaxhighlight>
Line 566 ⟶ 604:
Alternatively, you can initialize an empty map and then add items:
<syntaxhighlight lang=
phoneBook.set("Sally Smart", "555-9999");
phoneBook.set("John Doe", "555-1212");
Line 574 ⟶ 612:
=====Access by key=====
Accessing an element of the map can be done with the
<syntaxhighlight lang=
</syntaxhighlight>
In this example, the
=====Enumeration=====
The keys in a map are ordered. Thus, when iterating through it, a map object returns keys in order of insertion. The following demonstrates enumeration using a for-loop:
<syntaxhighlight lang=
// loop through the collection and display each entry.
for (const [name, number] of phoneBook) {
console.log(
}
</syntaxhighlight>
Line 594 ⟶ 632:
A key can be removed as follows:
<syntaxhighlight lang=
phoneBook.delete("Sally Smart");
</syntaxhighlight>
Line 603 ⟶ 641:
However, there are important differences that make a map preferable in certain cases. In JavaScript an object is a mapping from property names to values—that is, an associative array with one caveat: the keys of an object must be either a string or a symbol (native objects and primitives implicitly converted to a string keys are allowed). Objects also include one feature unrelated to associative arrays: an object has a prototype, so it contains default keys that could conflict with user-defined keys. So, doing a lookup for a property will point the lookup to the prototype's definition if the object does not define the property.
An object literal is written as <code>{ property1
<syntaxhighlight lang=
};
</syntaxhighlight>
To prevent the lookup from using the prototype's properties, you can use the <code>Object.setPrototypeOf</code> function:
<syntaxhighlight lang=JavaScript>
Line 619 ⟶ 657:
</syntaxhighlight>
As of ECMAScript 5 (ES5), the prototype can also be bypassed by using <code>Object.create(null)</code>:
<syntaxhighlight lang=JavaScript>
Object.assign(myObject, {
});
</syntaxhighlight>
Line 634 ⟶ 672:
<syntaxhighlight lang=JavaScript>
</syntaxhighlight>
Line 647 ⟶ 685:
<syntaxhighlight lang=JavaScript>
for (
}
</syntaxhighlight>
Line 656 ⟶ 694:
<syntaxhighlight lang=JavaScript>
for (const [property, value] of Object.entries(myObject)) {
}
</syntaxhighlight>
Line 670 ⟶ 708:
<syntaxhighlight lang=JavaScript>
myObject[1]
myObject[[
myObject[{ toString
</syntaxhighlight>
In modern JavaScript it's considered bad form to use the Array type as an associative array. Consensus is that the Object type and <code>Map</code>/<code>WeakMap</code> classes are best for this purpose. The reasoning behind this is that if Array is extended via prototype and Object is kept pristine,
See [http://blog.metawrap.com/2006/05/30/june-6th-is-javascript-array-and-object-prototype-awareness-day/ JavaScript Array And Object Prototype Awareness Day] for more information on the issue.
Line 685 ⟶ 723:
Declare dictionary:
<syntaxhighlight lang="julia">
</syntaxhighlight>
Access element:
<syntaxhighlight lang="julia">
phonebook["Sally Smart"]
</syntaxhighlight>
Add element:
<syntaxhighlight lang="julia">
</syntaxhighlight>
Delete element:
<syntaxhighlight lang="julia">
delete!(phonebook, "Sally Smart")
</syntaxhighlight>
Get keys and values as [[Iterator#Implicit iterators|iterables]]:
<syntaxhighlight lang="julia">
keys(phonebook)
values(phonebook)
</syntaxhighlight>
===KornShell 93, and compliant shells===
Line 711 ⟶ 754:
Definition:
<syntaxhighlight lang="ksh">
phonebook=(["Sally Smart"]="555-9999" ["John Doe"]="555-1212" ["[[J. Random Hacker]]"]="555-1337");
</syntaxhighlight>
Dereference:
<syntaxhighlight lang="ksh">
</syntaxhighlight>
Line 743 ⟶ 785:
</syntaxhighlight>
This function can be construed as
<syntaxhighlight lang=Lisp>
Line 760 ⟶ 802:
</syntaxhighlight>
Searching for an entry by its key is performed via <code>assoc</code>, which might be configured for the test predicate and direction, especially searching the association list from its end to its front. The result, if positive, returns the entire entry cons, not only its value. Failure to obtain a matching key
<syntaxhighlight lang=Lisp>
Line 1,032 ⟶ 1,074:
<syntaxhighlight lang="mathematica">
</syntaxhighlight>
Line 1,040 ⟶ 1,082:
<syntaxhighlight lang="mathematica">
</syntaxhighlight>
Line 1,046 ⟶ 1,088:
<syntaxhighlight lang="mathematica">
</syntaxhighlight>
Line 1,099 ⟶ 1,141:
</syntaxhighlight>
In Mac OS X 10.5+ and iPhone OS, dictionary keys can be enumerated more concisely using the <code>NSFastEnumeration</code> construct:<ref>{{cite web |title=NSFastEnumeration Protocol Reference |url=https://developer.apple.com/documentation/Cocoa/Reference/NSFastEnumeration_protocol/ |date=2011 |archive-url=https://web.archive.org/web/20160313082808/https://developer.apple.com/library/mac/documentation/Cocoa/Reference/NSFastEnumeration_protocol/ |archive-date=13 March 2016 |website=Mac Developer Library |access-date=3 August 2020}}</ref>
<syntaxhighlight lang=ObjC>
Line 1,173 ⟶ 1,215:
</syntaxhighlight>
Note that in order to use <code>Map</code>, you have to provide the functor <code>Map.Make</code> with a module which defines the key type and the comparison function. The third-party library ExtLib provides a polymorphic version of functional maps, called <code>PMap</code>,<ref>{{cite web |title=Module PMap |url=http://ocaml-extlib.googlecode.com/svn/doc/apiref/PMap.html |date=2008 |archive-url=https://web.archive.org/web/20081211233540/http://ocaml-extlib.googlecode.com/svn/doc/apiref/PMap.html |archive-date=11 December 2008 |website=Ocaml-extlib |access-date=3 August 2020}}</ref> which is given a comparison function upon creation.
Lists of pairs and functional maps both provide a purely functional interface. By contrast, hash tables provide an imperative interface. For many operations, hash tables are significantly faster than lists of pairs and functional maps.
Line 1,183 ⟶ 1,225:
<syntaxhighlight lang=Java>
String[String] phoneBook = {
"Sally Smart" -> "555-9999",
"John Doe" -> "555-1212",
"J. Random Hacker" -> "553-1337"
};
Line 1,192 ⟶ 1,234:
// iterate over the values
for (String number : phoneBook) {
System.out.println(number);
}
Line 1,199 ⟶ 1,241:
// iterate over the keys
for (String name : phoneBook.keys) {
System.out.println(name + " -> " + phoneBook[name]);
}
// phoneBook[name] access a value by a key (it looks like java array access)
Line 1,210 ⟶ 1,252:
<syntaxhighlight lang=Java>
</syntaxhighlight>
Line 1,227 ⟶ 1,269:
</syntaxhighlight>
Accessing a hash element uses the syntax <code>$hash_name{$key}</code> – the key is surrounded by [[Bracket#
The list of keys and values can be extracted using the built-in functions <code>keys</code> and <code>values</code>, respectively. So, for example, to print all the keys of a hash:
Line 1,333 ⟶ 1,375:
===PHP===
[[PHP]]'s built-in array type is, in reality, an associative array. Even when using numerical indexes, PHP internally stores arrays as associative arrays.<ref>About the implementation of [http://se.php.net/manual/en/language.types.array.php Arrays] in PHP</ref> So, PHP can have non-consecutively numerically
An associative array can be declared using the following syntax:
<syntaxhighlight lang=
$phonebook = array();
$phonebook['Sally Smart'] = '555-9999';
Line 1,368 ⟶ 1,410:
PHP can loop through an associative array as follows:
<syntaxhighlight lang=
foreach ($phonebook as $name => $number) {
echo 'Number for ', $name, ': ', $number, "\n";
}
// For the last array example it is used like this
foreach ($phonebook['contacts'] as $name => $num) {
echo 'Name: ', $name, ', number: ', $num['number'], "\n";
}
</syntaxhighlight>
PHP has an extensive set of functions to operate on arrays.<ref>
Associative arrays that can use objects as keys, instead of strings and integers, can be implemented with the <code>SplObjectStorage</code> class from the Standard PHP Library (SPL).<ref>{{cite web |title=The SplObjectStorage class |url=http://php.net/SplObjectStorage |website=PHP.net |access-date=3 August 2020}}</ref>
===Pike===
[[Pike (programming language)|Pike]] has built-in support for associative arrays, which are referred to as mappings. Mappings are created as follows:
<syntaxhighlight lang=
mapping(string:string) phonebook = ([
"Sally Smart":"555-9999",
Line 1,398 ⟶ 1,440:
Iterating through a mapping can be done using <code>foreach</code>:
<syntaxhighlight lang="pike">
foreach(phonebook; string key; string value) {
write("%s:%s\n", key, value);
Line 1,406 ⟶ 1,448:
Or using an iterator object:
<syntaxhighlight lang="pike">
Mapping.Iterator i = get_iterator(phonebook);
while (i->index()) {
Line 1,416 ⟶ 1,458:
Elements of a mapping can be removed using <code>m_delete</code>, which returns the value of the removed index:
<syntaxhighlight lang="pike">
string sallys_number = m_delete(phonebook, "Sally Smart");
</syntaxhighlight>
===
In [[PostScript]], associative arrays are called dictionaries. In Level 1 PostScript they must be created explicitly, but Level 2 introduced direct declaration using
<syntaxhighlight lang="postscript">
Line 1,440 ⟶ 1,482:
% Both methods leave the dictionary on the operand stack
</syntaxhighlight>
Dictionaries can be accessed directly, using <code>get</code>, or implicitly, by placing the dictionary on the dictionary stack using <code>begin</code>:
<syntaxhighlight lang="postscript">
Line 1,451 ⟶ 1,494:
</syntaxhighlight>
Dictionary contents can be iterated through using
<syntaxhighlight lang="postscript">
Line 1,461 ⟶ 1,504:
>> {exch =print ( is ) print ==} forall
</syntaxhighlight>
Which may output:
<syntaxhighlight lang="postscript">
That is 2
Line 1,468 ⟶ 1,513:
</syntaxhighlight>
Dictionaries can be augmented (up to their defined size only in Level 1) or altered using
<syntaxhighlight lang="postscript">
% define a dictionary for easy reuse:
Line 1,488 ⟶ 1,533:
=== Prolog ===
Some versions of [[Prolog]] include dictionary ("
===
In [[Python (programming language)|Python]], associative arrays are called
<syntaxhighlight lang=
phonebook = {
}
</syntaxhighlight>
<syntaxhighlight lang=
>>> phonebook[
'555-9999'
</syntaxhighlight>
Loop [[iterator#Python|iterating]] through all the keys of the dictionary:
<syntaxhighlight lang="python">
>>> for key in phonebook:
... print(key, phonebook[key])
Line 1,520 ⟶ 1,564:
Iterating through (key, value) tuples:
<syntaxhighlight lang=
>>> for key, value in phonebook.items():
... print(key, value)
Line 1,528 ⟶ 1,572:
</syntaxhighlight>
Dictionary keys can be individually deleted using the <code>del</code> statement. The corresponding value can be returned before the key-value pair
<syntaxhighlight lang=
>>> del phonebook[
>>> val = phonebook.pop(
>>> phonebook.keys() # Only one key left
['J. Random Hacker']
</syntaxhighlight>
Python 2.7 and 3.x also
<syntaxhighlight lang="python">
>>> square_dict = {i: i*i for i in range(5)}
>>> square_dict
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
>>> {key: value for key, value in phonebook.items() if
{'J. Random Hacker': '553-1337', 'John Doe': '555-1212'}
</syntaxhighlight>
Strictly speaking, a dictionary is a super-set of an associative array, since neither the keys or values are limited to a single datatype. One could think of a dictionary as an
<syntaxhighlight lang=
phonebook = {
14:
}
</syntaxhighlight>
Line 1,559 ⟶ 1,604:
The dictionary keys must be of an [[Immutable object|immutable]] data type. In Python, strings are immutable due to their method of implementation.
===
In [[Red (programming language)|Red]] the built-in <code>map!</code><ref>{{cite web|url=https://doc.red-lang.org/en/datatypes/map.html|title=Map! datatype|website=doc.red-lang.org}}</ref> datatype provides an associative array
A map can be written as a literal, such
<syntaxhighlight lang=
Red [Title:"My map"]
Line 1,604 ⟶ 1,649:
</syntaxhighlight>
===
In [[REXX]], associative arrays are called
<syntaxhighlight lang=
KEY = 'Sally Smart'
PHONEBOOK.KEY = '555-9999'
Line 1,616 ⟶ 1,661:
</syntaxhighlight>
Stem variables with numeric keys typically start at 1 and go up from there. The 0
<syntaxhighlight lang=
NAME.1 = 'Sally Smart'
NAME.2 = 'John Doe'
Line 1,626 ⟶ 1,671:
</syntaxhighlight>
REXX has no easy way of automatically accessing the keys
keys are stored in a separate associative array, with numeric keys.
===
In [[Ruby programming language|Ruby]] a hash table is used as follows:
<syntaxhighlight lang="rb">
phonebook = {
'Sally Smart' => '555-9999',
'John Doe' => '555-1212',
}
phonebook['John Doe']
</syntaxhighlight>
Ruby supports hash looping and iteration with the following syntax:
<syntaxhighlight lang="irb">
irb(main):007:0> ### iterate over keys and values
irb(main):008:0* phonebook.each {|key, value| puts key + " => " + value}
Line 1,669 ⟶ 1,711:
Ruby also supports many other useful operations on hashes, such as merging hashes, selecting or rejecting elements that meet some criteria, inverting (swapping the keys and values), and flattening a hash into an array.
===Rust===
The [[Rust (programming language)|Rust]] standard library provides a hash map (<code>std::collections::HashMap</code>) and a [[B-tree]] map (<code>std::collections::BTreeMap</code>). They share several methods with the same names, but have different requirements for the types of keys that can be inserted. The <code>HashMap</code> requires keys to implement the <code>Eq</code> ([[equivalence relation]]) and <code>Hash</code> (hashability) traits and it stores entries in an unspecified order, and the <code>BTreeMap</code> requires the <code>Ord</code> ([[total order]]) trait for its keys and it stores entries in an order defined by the key type. The order is reflected by the default iterators.
<syntaxhighlight lang="rust">
use std::collections::HashMap;
let mut phone_book = HashMap::new();
phone_book.insert("Sally Smart", "555-9999");
phone_book.insert("John Doe", "555-1212");
phone_book.insert("J. Random Hacker", "555-1337");
</syntaxhighlight>
The default iterators visit all entries as tuples. The <code>HashMap</code> iterators visit entries in an unspecified order and the <code>BTreeMap</code> iterator visits entries in the order defined by the key type.
<syntaxhighlight lang="rust">
for (name, number) in &phone_book {
println!("{} {}", name, number);
}
</syntaxhighlight>
There is also an iterator for keys:
<syntaxhighlight lang="rust">
for name in phone_book.keys() {
println!("{}", name);
}
</syntaxhighlight>
===S-Lang===
[[S-Lang]] has an associative array type:
<syntaxhighlight lang="text">
Line 1,681 ⟶ 1,746:
</syntaxhighlight>
You can also loop through an associated array in a number of ways
<syntaxhighlight lang="text">
Line 1,700 ⟶ 1,764:
</syntaxhighlight>
===
[[Scala (programming language)|Scala]] provides an immutable <code>Map</code> class as part of the <code>scala.collection</code> framework:
<syntaxhighlight lang=
val phonebook = Map("Sally Smart" -> "555-9999",
"John Doe" -> "555-1212",
Line 1,709 ⟶ 1,773:
</syntaxhighlight>
Scala's [[type inference]] will
<syntaxhighlight lang=
phonebook.get("Sally Smart")
</syntaxhighlight>
This returns an <code>Option</code> type, Scala's equivalent of
===
In [[Smalltalk]] a
<syntaxhighlight lang=
phonebook := Dictionary new.
phonebook at: 'Sally Smart' put: '555-9999'.
Line 1,727 ⟶ 1,791:
</syntaxhighlight>
To access an entry the message <code>#at:</code> is sent to the dictionary object
<syntaxhighlight lang=
phonebook at: 'Sally Smart'
</syntaxhighlight>
Which gives:
<syntaxhighlight lang=
'555-9999'
</syntaxhighlight>
A dictionary hashes, or compares, based on equality and marks both key and value as
[[Garbage collection (computer science)#Strong and weak references|strong references]]. Variants exist in which hash/compare on identity (IdentityDictionary) or keep [[Garbage collection (computer science)#Strong and weak references|weak references]] (WeakKeyDictionary / WeakValueDictionary).
Because every object implements #hash, any object can be used as key (and of course also as value).
===
[[SNOBOL]] is one of the first (if not the first) programming languages to use associative arrays. Associative arrays in SNOBOL are called Tables.
<syntaxhighlight lang="snobol">
Line 1,753 ⟶ 1,817:
</syntaxhighlight>
===
The SML'97 standard of the [[Standard ML]] programming language does not provide any associative containers. However, various implementations of Standard ML do provide associative containers.
The library of the popular [[Standard ML of New Jersey]] (SML/NJ) implementation provides a signature (somewhat like an "interface"), <code>ORD_MAP</code>, which defines a common interface for ordered functional (immutable) associative arrays. There are several general
<syntaxhighlight lang="sml">
Line 1,801 ⟶ 1,865:
</syntaxhighlight>
Monomorphic hash tables are also supported, using the <code>HashTableFn</code> functor.
Another Standard ML implementation, [[Moscow ML]], also provides some associative containers. First, it provides polymorphic hash tables in the <code>Polyhash</code> structure. Also, some functional maps from the SML/NJ library above are available as <code>Binarymap</code>, <code>Splaymap</code>, and <code>Intmap</code> structures.
===
There are two [[Tcl]] facilities that support associative
====array====
<syntaxhighlight lang=Tcl>
set {phonebook(Sally Smart)} 555-9999
Line 1,837 ⟶ 1,880:
</syntaxhighlight>
If there is a
Alternatively, several array elements can be set
<syntaxhighlight lang=Tcl>
Line 1,845 ⟶ 1,888:
</syntaxhighlight>
To access one array entry and put it
<syntaxhighlight lang=Tcl>
Line 1,851 ⟶ 1,894:
</syntaxhighlight>
Which returns this result:
<syntaxhighlight lang=Text>
Line 1,869 ⟶ 1,912:
</syntaxhighlight>
===
<syntaxhighlight lang=Tcl>
set phonebook [dict create {Sally Smart} 555-9999 {John Doe} 555-1212 {J. Random Hacker} 553-1337]
</syntaxhighlight>
To look up an item:
<syntaxhighlight lang=Tcl>
dict get $phonebook {John Doe}
</syntaxhighlight>
To iterate through a dict:
<syntaxhighlight lang=Tcl>
foreach {name number} $phonebook {
puts "name: $name\nnumber: $number"
}
</syntaxhighlight>
=== Visual Basic ===
[[Visual Basic]] can use the Dictionary class from the [[Windows Scripting Host|Microsoft Scripting Runtime]] (which is shipped with Visual Basic 6). There is no standard implementation common to all versions:
<syntaxhighlight lang=
' Requires a reference to SCRRUN.DLL in Project Properties
Dim phoneBook As New Dictionary
Line 1,883 ⟶ 1,945:
</syntaxhighlight>
===
[[Visual Basic .NET]] uses the collection classes provided by the [[.NET Framework]].
====Creation====
The following code demonstrates the creation and population of a dictionary (see [[#C#|the C# example on this page]] for additional information):
<syntaxhighlight lang=VBNet>
Dim dic As New System.Collections.Generic.Dictionary(Of String, String)
Line 1,896 ⟶ 1,958:
</syntaxhighlight>
An
<syntaxhighlight lang=VBNet>
Dim dic As New System.Collections.Dictionary(Of String, String) From {
Line 1,906 ⟶ 1,969:
====Access by key====
Example demonstrating access (see [[#C# access|C# access]]):
<syntaxhighlight lang=VBNet>
Dim sallyNumber = dic("Sally Smart")
Line 1,919 ⟶ 1,982:
====Enumeration====
Example demonstrating enumeration (see [[#C# enumeration]]):
<syntaxhighlight lang=VBNet>
' loop through the collection and display each entry.
Line 1,928 ⟶ 1,991:
</syntaxhighlight>
===
Unlike many other [[command line interpreter]]s, [[Windows PowerShell]] has built-in, language-level support for defining associative arrays
<syntaxhighlight lang=PowerShell>
Line 1,941 ⟶ 2,002:
</syntaxhighlight>
<syntaxhighlight lang=PowerShell>
Line 1,947 ⟶ 2,008:
</syntaxhighlight>
Entries can be separated by either a semicolon or a newline
<syntaxhighlight lang=PowerShell>
Line 1,956 ⟶ 2,017:
</syntaxhighlight>
Keys and values can be any [[.NET Framework|.NET]] object type
<syntaxhighlight lang=PowerShell>
Line 1,967 ⟶ 2,028:
</syntaxhighlight>
It is also possible to create an empty associative array and add single entries, or even other associative arrays, to it later on
<syntaxhighlight lang=PowerShell>
Line 1,975 ⟶ 2,036:
</syntaxhighlight>
New entries can also be added by using the array index operator, the property operator, or the <code>Add()</code> method of the underlying .NET object:
<syntaxhighlight lang=PowerShell>
Line 1,984 ⟶ 2,045:
</syntaxhighlight>
To dereference assigned objects, the array index operator, the property operator, or the parameterized property <code>Item()</code> of the .NET object can be used:
<syntaxhighlight lang=PowerShell>
Line 2,004 ⟶ 2,065:
</syntaxhighlight>
Hash tables can be added
<syntaxhighlight lang=PowerShell>
Line 2,017 ⟶ 2,078:
Many data serialization formats also support associative arrays (see [[Comparison of data serialization formats#Syntax comparison of human-readable formats|this table]])
===
In [[JSON]], associative arrays are also referred to as objects. Keys can only be strings.
<syntaxhighlight lang=JavaScript>
{
Line 2,027 ⟶ 2,089:
</syntaxhighlight>
===
[[TOML]] is designed to map directly to a hash map. TOML refers to associative arrays as tables. Tables within TOML can be expressed in either an "unfolded" or an inline approach. Keys can only be strings.<syntaxhighlight lang="toml">[phonebook]
"Sally Smart" = "555-9999"
"John Doe" = "555-1212"
"J. Random Hacker" = "555-1337"</syntaxhighlight><syntaxhighlight lang="toml">
phonebook = { "Sally Smart" = "555-9999", "John Doe" = "555-1212", "J. Random Hacker" = "555-1337" }
</syntaxhighlight>
===YAML===
[[YAML]] associative arrays are also called map elements or key-value pairs. YAML places no restrictions on the types of keys; in particular, they are not restricted to being scalar or string values.
<syntaxhighlight lang=YAML>
|