Collections: Difference between revisions

m
imported>Arakov
 
(10 intermediate revisions by 9 users not shown)
Line 17:
=={{header|11l}}==
11l supports arrays, tuples, dictionaries, sets, and double-ended queues as built-in collection types. See http://11l-lang.org/doc/built-in-types for further details.
=={{header|68000 Assembly}}==
(I'm probably going to use the words "array" and "collection" interchangeably, apologizing in advance here.)
 
Like nearly all data structures in assembly, a collection is just a sequence of values in memory. They need not share the same data type, however mixing byte data with word/long data can cause problems with alignment if the byte data is not correctly padded. Nothing is stopping you from interpreting data the "wrong" way, which can be handy for situations where you need to "deep-copy" an array of bytes and number of elements in that array just happens to be a multiple of 4 (meaning that you can treat the data as longs and copy it more quickly).
 
For collections of data whose elements are more than 4 bytes in size, or have varying lengths (such as strings), it's best to store a collection of pointers to those elements rather than the elements themselves. Reason being, pointers are always 4 bytes (i.e. a "long") on the 68000, regardless of the length of whatever it is they point to. This makes it <b>much easier</b> to find the beginning of a desired string, since you don't have to know each string's length in order to (for example) load the 5th string in the collection
 
In this example, we're creating a collection of strings associated with the vector table of the 68000's CPU. It's not too important what this data represents, it's more to showcase an actual application of the concept of a collection of pointers being more convenient than a collection of actual strings, so don't worry if you don't understand what these strings mean.
 
<syntaxhighlight lang="68000devpac"> dc.l TrapString_Bus
dc.l TrapString_Addr
dc.l TrapString_Illegal
dc.l TrapString_Div0
dc.l TrapString_chk
dc.l TrapString_v
dc.l TrapString_priv
dc.l TrapString_trace
TrapString_Bus:
dc.b "Bus error",255
even
TrapString_Addr:
dc.b "Address error",255
even
TrapString_Illegal:
dc.b "Illegal Instruction",255
even
TrapString_Div0:
dc.b "Divide By Zero",255
even
TrapString_chk:
dc.b "CHK Failure",255
even
TrapString_v:
dc.b "Signed Overflow",255
even
TrapString_priv:
dc.b "Privilege Violation",255
even
TrapString_trace:
dc.b "Tracing",255
even</syntaxhighlight>
 
As mentioned earlier, 68000 Assembly doesn't know (or care) what types of data are stored in an array or collection, although if you try to read from an odd memory address at word or long length your CPU will suffer an alignment fault. The CPU doesn't care what types of data are actually stored in an array. It's the programmer's job to tell the CPU what the data actually means.
 
=={{header|ABAP}}==
 
<syntaxhighlight lang="abap">
<lang ABAP>
REPORT z_test_rosetta_collection.
 
Line 39 ⟶ 83:
START-OF-SELECTION.
NEW lcl_collection( )->start( ).
</syntaxhighlight>
</lang>
 
=={{header|Ada}}==
Line 50 ⟶ 94:
Anonymous arrays have no type associated with them that is accessible to the programmer. This means that anonymous arrays cannot be compared in the aggregate to other arrays (even those with the same index structure and contained type) or passed as a parameter to a subprogram. For these reasons, anonymous arrays are best used as singletons and global constants.
 
<langsyntaxhighlight Adalang="ada">procedure Array_Collection is
 
A : array (-3 .. -1) of Integer := (1, 2, 3);
Line 60 ⟶ 104:
A (-1) := 1;
end Array_Collection;</langsyntaxhighlight>
 
===array types===
Because of the limitations of anonymous arrays noted above, arrays are more typically defined in Ada as array types, as in the example below.
 
<langsyntaxhighlight Adalang="ada">procedure Array_Collection is
 
type Array_Type is array (1 .. 3) of Integer;
Line 76 ⟶ 120:
A (3) := 1;
end Array_Collection;</langsyntaxhighlight>
 
===unconstrained arrays===
Dynamic arrays can be created through the use of pointers to unconstrained arrays. While an unconstrained array's index type is defined, it does not have a pre-defined range of indices - they are specified at the time of declaration or, as would be the case in a dynamic array, at the time the memory for the array is allocated. The creation of a dynamic array is not shown here, but below is an example declaration of an unconstrained array in Ada.
 
<langsyntaxhighlight Adalang="ada">procedure Array_Collection is
 
type Array_Type is array (positive range <>) of Integer; -- may be indexed with any positive
Line 93 ⟶ 137:
A (3) := 1;
end Array_Collection;</langsyntaxhighlight>
 
===doubly linked lists===
Line 100 ⟶ 144:
{{libheader|Ada.Containers.Doubly_Linked_Lists}}
 
<langsyntaxhighlight Adalang="ada">with Ada.Containers.Doubly_Linked_Lists;
use Ada.Containers;
 
Line 116 ⟶ 160:
DL_List.Append (3);
end Doubly_Linked_List;</langsyntaxhighlight>
 
===vectors===
Line 123 ⟶ 167:
{{libheader|Ada.Containers.Vectors}}
 
<langsyntaxhighlight Adalang="ada">with Ada.Containers.Vectors;
use Ada.Containers;
 
Line 139 ⟶ 183:
V.Append (3);
end Vector_Example;</langsyntaxhighlight>
 
=={{header|Aime}}==
Line 146 ⟶ 190:
===Lists===
Declaring a list:
<syntaxhighlight lang ="aime">list l;</langsyntaxhighlight>
Adding values to it:
<langsyntaxhighlight lang="aime">l_p_integer(l, 0, 7);
l_push(l, "a string");
l_append(l, 2.5);</langsyntaxhighlight>
Retrieving values from a list:
<langsyntaxhighlight lang="aime">l_query(l, 2)
l_head(l)
l_q_text(l, 1)
l[3]</langsyntaxhighlight>
 
===Records===
Declaring a record:
<syntaxhighlight lang ="aime">record r;</langsyntaxhighlight>
Adding values to it:
<langsyntaxhighlight lang="aime">r_p_integer(r, "key1", 7);
r_put(r, "key2", "a string");
r["key3"] = .25;</langsyntaxhighlight>
Retrieving values from a record:
<langsyntaxhighlight lang="aime">r_query(r, "key1")
r_tail(r)
r["key2"]</langsyntaxhighlight>
 
=={{header|ALGOL 68}}==
Arrays are the closest thing to collections available as standard in Algol 68. Collections could be implemented using STRUCTs but there are none as standard. Some examples of arrays:
<langsyntaxhighlight lang="algol68"># create a constant array of integers and set its values #
[]INT constant array = ( 1, 2, 3, 4 );
# create an array of integers that can be changed, note the size mst be specified #
Line 192 ⟶ 236:
# replace it with a new array of 5 elements #
fa := LOC[ -2 : 2 ]INT;
</syntaxhighlight>
</lang>
 
=={{header|Apex}}==
Line 198 ⟶ 242:
A list is an ordered collection of elements that are distinguished by their indices
Creating Lists
<langsyntaxhighlight lang="apex">
// Create an empty list of String
List<String> my_list = new List<String>();
// Create a nested list
List<List<Set<Integer>>> my_list_2 = new List<List<Set<Integer>>>();
</syntaxhighlight>
</lang>
Access elements in a list
<langsyntaxhighlight lang="apex">
List<Integer> myList = new List<Integer>(); // Define a new list
myList.add(47); // Adds a second element of value 47 to the end
Line 212 ⟶ 256:
myList.set(0, 1); // Adds the integer 1 to the list at index 0
myList.clear(); // Removes all elements from the list
</syntaxhighlight>
</lang>
Using Array Notation for One-dimensional list
<langsyntaxhighlight lang="apex">
String[] colors = new List<String>();
List<String> colors = new String[1];
colors[0] = 'Green';
</syntaxhighlight>
</lang>
 
===Sets===
A set is an unordered collection of elements that do not contain any duplicates.
Defining a set:
<langsyntaxhighlight lang="apex">
Set<String> s1 = new Set<String>{'a', 'b + c'}; // Defines a new set with two elements
Set<String> s2 = new Set<String>(s1); // Defines a new set that contains the
// elements of the set created in the previous step
</syntaxhighlight>
</lang>
Access elements in a set:
<langsyntaxhighlight lang="apex">
Set<Integer> s = new Set<Integer>(); // Define a new set
s.add(1); // Add an element to the set
System.assert(s.contains(1)); // Assert that the set contains an element
s.remove(1); // Remove the element from the set
</syntaxhighlight>
</lang>
Note the following limitations on sets:
* Unlike Java, Apex developers do not need to reference the algorithm that is used to implement a set in their declarations (for example, HashSet or TreeSet). Apex uses a hash structure for all sets.
Line 243 ⟶ 287:
A map is a collection of key-value pairs where each unique key maps to a single value
Declaring a map:
<langsyntaxhighlight lang="apex">
Map<String, String> country_currencies = new Map<String, String>();
Map<ID, Set<String>> m = new Map<ID, Set<String>>();
Map<String, String> MyStrings = new Map<String, String>{'a' => 'b', 'c' => 'd'.toUpperCase()};
</syntaxhighlight>
</lang>
Accessing a Map:
<langsyntaxhighlight lang="apex">
Map<Integer, String> m = new Map<Integer, String>(); // Define a new map
m.put(1, 'First entry'); // Insert a new key-value pair in the map
Line 257 ⟶ 301:
System.assertEquals('Second entry', value);
Set<Integer> s = m.keySet(); // Return a set that contains all of the keys in the map
</syntaxhighlight>
</lang>
Map Considerations:
* Unlike Java, Apex developers do not need to reference the algorithm that is used to implement a map in their declarations (for example, HashMap or TreeMap). Apex uses a hash structure for all maps.
Line 272 ⟶ 316:
===Array===
 
<langsyntaxhighlight lang="rebol">; initialize array
arr: ["one" 2 "three" "four"]
Line 279 ⟶ 323:
 
; print it
print arr</langsyntaxhighlight>
 
{{out}}
Line 287 ⟶ 331:
===Dictionary===
 
<langsyntaxhighlight lang="rebol">; initialize dictionary
dict: #[
name: "john"
Line 299 ⟶ 343:
; print it
print dict</langsyntaxhighlight>
 
{{out}}
Line 309 ⟶ 353:
{{works with|AutoHotkey_L}}
[http://l.autohotkey.net/docs/Objects.htm Documentation]
<langsyntaxhighlight AutoHotkeylang="autohotkey">myCol := Object()
mycol.mykey := "my value!"
mycol["mykey"] := "new val!"
MsgBox % mycol.mykey ; new val</langsyntaxhighlight>
 
===Pseudo-arrays===
Documentation: http://www.autohotkey.com/docs/misc/Arrays.htm
<langsyntaxhighlight AutoHotkeylang="autohotkey">Loop 3
array%A_Index% := A_Index * 9
MsgBox % array1 " " array2 " " array3 ; 9 18 27</langsyntaxhighlight>
===Structs===
Structs are not natively supported in AutoHotkey, however they are often required in DllCalls to C++ Dlls.
This shows how to retrieve values from a RECT structure in AutoHotkey (from the DllCall documentation at http://www.autohotkey.com/docs/commands/DllCall.htm)
<langsyntaxhighlight AutoHotkeylang="autohotkey">VarSetCapacity(Rect, 16) ; A RECT is a struct consisting of four 32-bit integers (i.e. 4*4=16).
DllCall("GetWindowRect", UInt, WinExist(), UInt, &Rect) ; WinExist() returns an HWND.
MsgBox % "Left " . NumGet(Rect, 0, true) . " Top " . NumGet(Rect, 4, true)
. " Right " . NumGet(Rect, 8, true) . " Bottom " . NumGet(Rect, 12, true)</langsyntaxhighlight>
 
=={{header|AWK}}==
In awk, the closest thing to collections would be arrays. They are created when needed at assignment
<langsyntaxhighlight lang="awk">a[0]="hello"</langsyntaxhighlight>
or by splitting a string
<langsyntaxhighlight lang="awk">split("one two three",a)</langsyntaxhighlight>
Single elements are accessible with the bracket notation, like in C:
<syntaxhighlight lang ="awk">print a[0]</langsyntaxhighlight>
One can iterate over the elements of an array:
<langsyntaxhighlight lang="awk">for(i in a) print i":"a[i]</langsyntaxhighlight>
 
=={{header|Axe}}==
<langsyntaxhighlight lang="axe">1→{L₁}
2→{L₁+1}
3→{L₁+2}
Line 345 ⟶ 389:
Disp {L₁+1}►Dec,i
Disp {L₁+2}►Dec,i
Disp {L₁+3}►Dec,i</langsyntaxhighlight>
 
=={{header|BBC BASIC}}==
===Arrays===
In BBC BASIC the only native type of 'collection' is the array; the index starts at zero and the subscript specified in the DIM is the highest value of the index. Hence in this example an array with two elements is defined:
<langsyntaxhighlight lang="bbcbasic"> DIM text$(1)
text$(0) = "Hello "
text$(1) = "world!"</langsyntaxhighlight>
===Arrays of structures===
{{works with|BBC BASIC for Windows}}
When the objects in the collection are not simple scalar types an array of structures may be used:
<langsyntaxhighlight lang="bbcbasic"> DIM collection{(1) name$, year%}
collection{(0)}.name$ = "Richard"
collection{(0)}.year% = 1952
collection{(1)}.name$ = "Sue"
collection{(1)}.year% = 1950</langsyntaxhighlight>
===Linked lists===
Although not a native language feature, other types of collections such as linked lists may be constructed:
<langsyntaxhighlight lang="bbcbasic"> DIM node{name$, year%, link%}
list% = 0
PROCadd(list%, node{}, "Richard", 1952)
Line 386 ⟶ 430:
l% = c.link%
ENDWHILE
ENDPROC</langsyntaxhighlight>
 
=={{header|bc}}==
Line 396 ⟶ 440:
One thing in C language proper that can be said to be a collection is array type.
An array has a length known at compile time.
<langsyntaxhighlight lang="c">#define cSize( a ) ( sizeof(a)/sizeof(a[0]) ) /* a.size() */
int ar[10]; /* Collection<Integer> ar = new ArrayList<Integer>(10); */
ar[0] = 1; /* ar.set(0, 1); */
Line 406 ⟶ 450:
p++) { /* pValue=p.next() ) { */
printf("%d\n",*p); /* System.out.println(pValue); */
} /* } */</langsyntaxhighlight>
Please note that c built-in pointer-arithmetic support which helps this logic. An integer may be 4 bytes, and a char 1 byte: the plus operator (+) is overloaded to multiply a incement by 4 for integer pointers and by 1 for char pointers (etc).
 
Another construct which can be seen as a collection is a malloced array. The size of a malloced array is not known at compile time.
<syntaxhighlight lang="c">
<lang c>
int* ar; /* Collection<Integer> ar; */
int arSize;
Line 422 ⟶ 466:
p++) { /* pValue=p.next() ) { */
printf("%d\n",*p); /* System.out.println(pValue); */
} /* } */</langsyntaxhighlight>
 
A string is another C language construct (when looked at with its standard libraries) that behaves like a collection.
Line 432 ⟶ 476:
 
===Arrays===
<langsyntaxhighlight lang="csharp">
// Creates and initializes a new integer Array
int[] intArray = new int[5] { 1, 2, 3, 4, 5 };
Line 443 ⟶ 487:
string[] stringArr = new string[5];
stringArr[0] = "string";
</syntaxhighlight>
</lang>
 
===ArrayList and List===
The size of ArrayList is dynamically increased as required. ArrayLists are zero-based.
<langsyntaxhighlight lang="csharp">
//Create and initialize ArrayList
ArrayList myAl = new ArrayList { "Hello", "World", "!" };
Line 457 ⟶ 501:
myAL.Add("!");
 
</syntaxhighlight>
</lang>
 
The List class is the generic equivalent of the ArrayList class.
A List is a strongly typed list of objects that can be accessed by index ( zero-based again).
<langsyntaxhighlight lang="csharp">
//Create and initialize List
List<string> myList = new List<string> { "Hello", "World", "!" };
Line 470 ⟶ 514:
myList2.Add("World");
myList2.Add("!");
</syntaxhighlight>
</lang>
 
===Hashtable and Dictionary===
Hashtables represent a collection of key/value pairs that are organized based on the hash code of the key.
Keys must be unique.
<langsyntaxhighlight lang="csharp">
//Create an initialize Hashtable
Hashtable myHt = new Hashtable() { { "Hello", "World" }, { "Key", "Value" } };
Line 483 ⟶ 527:
myHt2.Add("Hello", "World");
myHt2.Add("Key", "Value");
</syntaxhighlight>
</lang>
Dictionary is a generic class.It represents a collection of key/value pairs. Keys must be unique.
<langsyntaxhighlight lang="csharp">
//Create an initialize Dictionary
Dictionary<string, string> dict = new Dictionary<string, string>() { { "Hello", "World" }, { "Key", "Value" } };
Line 492 ⟶ 536:
dict2.Add("Hello", "World");
dict2.Add("Key", "Value");
</syntaxhighlight>
</lang>
 
=={{header|C++}}==
Line 502 ⟶ 546:
The simplest collection in C++ is the built-in array. Built-in arrays have a fixed size, and except for POD types (i.e. basically any type you culd also write in C), the members are all initialized at array creation time (if no explicit initialization is done, the default constructr is used).
 
<langsyntaxhighlight lang="cpp">int a[5]; // array of 5 ints (since int is POD, the members are not initialized)
a[0] = 1; // indexes start at 0
 
Line 509 ⟶ 553:
#include <string>
std::string strings[4]; // std::string is no POD, therefore all array members are default-initialized
// (for std::string this means initialized with empty strings)</langsyntaxhighlight>
 
===vector===
A vector is basically a resizable array. It is optimized for adding/removing elements on the end, and fast access to elements anywhere. Inserting elements at the beginning or in the middle is possible, but in general inefficient.
 
<langsyntaxhighlight lang="cpp">#include <vector>
 
std::vector<int> v; // empty vector
v.push_back(5); // insert a 5 at the end
v.insert(v.begin(), 7); // insert a 7 at the beginning</langsyntaxhighlight>
 
===deque===
A deque is optimized for appending and removing elements on both ends ofd the array. Accessing random elements is still efficient, but slightly less than with vector.
 
<langsyntaxhighlight lang="cpp">#include <deque>
 
std::deque<int> d; // empty deque
d.push_back(5); // insert a 5 at the end
d.push_front(7); // insert a 7 at the beginning
d.insert(v.begin()+1, 6); // insert a 6 in the middle</langsyntaxhighlight>
 
===list===
A list is optimized for insertion at an arbitrary place (provided you already have an iterator pointing to that place). Element access is efficient only in linear order.
 
<langsyntaxhighlight lang="cpp">#include <list>
 
std::list<int> l; // empty list
Line 540 ⟶ 584:
std::list::iterator i = l.begin();
++l;
l.insert(i, 6); // insert a 6 in the middle</langsyntaxhighlight>
 
===set===
A set keeps the inserted elements sorted, and also makes sure that each element occurs only once. Of course, if you want to put something into a set, it must be less-than-comparable, i.e. you must be able to compare which of two objects <tt>a</tt> and <tt>b</tt> is smaller using <tt>a<b</tt> (there's also a way to define sets with an user-defined order, in which case this restriction doesn't apply).
 
<langsyntaxhighlight lang="cpp">#include <set>
 
std::set<int> s; // empty set
s.insert(5); // insert a 5
s.insert(7); // insert a 7 (automatically placed after the 5)
s.insert(5); // try to insert another 5 (will not change the set)</langsyntaxhighlight>
 
===multiset===
A multiset is like a set, except the same element may occur multiple times.
 
<langsyntaxhighlight lang="cpp">#include <multiset>
 
std::multiset<int> m; // empty multiset
m.insert(5); // insert a 5
m.insert(7); // insert a 7 (automatically placed after the 5)
m.insert(5); // insert a second 5 (now m contains two 5s, followed by one 7)</langsyntaxhighlight>
 
=={{header|Clojure}}==
Line 566 ⟶ 610:
 
===Hash maps===
<langsyntaxhighlight Clojurelang="clojure">{1 "a", "Q" 10} ; commas are treated as whitespace
(hash-map 1 "a" "Q" 10) ; equivalent to the above
(let [my-map {1 "a"}]
(assoc my-map "Q" 10)) ; "adding" an element</langsyntaxhighlight>
===Lists===
<langsyntaxhighlight Clojurelang="clojure">'(1 4 7) ; a linked list
(list 1 4 7)
(cons 1 (cons 4 '(7)))</langsyntaxhighlight>
 
===Vectors===
<langsyntaxhighlight Clojurelang="clojure">['a 4 11] ; somewhere between array and list
(vector 'a 4 11)
(cons ['a 4] 11) ; vectors add at the *end*</langsyntaxhighlight>
 
===Sets===
<langsyntaxhighlight Clojurelang="clojure">#{:pig :dog :bear}
(assoc #{:pig :bear} :dog)
(set [:pig :bear :dog])</langsyntaxhighlight>
 
=={{header|COBOL}}==
Line 593 ⟶ 637:
 
{{works with|GnuCOBOL}}
<langsyntaxhighlight COBOLlang="cobol"> identification division.
program-id. collections.
 
Line 629 ⟶ 673:
 
goback.
end program collections.</langsyntaxhighlight>
 
{{out}}
Line 653 ⟶ 697:
====hashing====
 
<langsyntaxhighlight lang="lisp">CL-USER> (let ((list '())
(hash-table (make-hash-table)))
(push 1 list)
Line 693 ⟶ 737:
(3 2 1)
[list]
; No value</langsyntaxhighlight>
 
====deque====
Line 699 ⟶ 743:
In Lisp, a deque can be represented using two list variables which are understood to be opposite to each other. That is to say, the list links (cons cell cdr pointers) go inward into the deque from both ends. For instance the deque (1 2 3 4 5 6) can be represented using (1 2 3) and (6 5 4). Then, it is easy to push items on either end using ordinary list push operations. Popping is also simple, except when the case occurs that either piece runs out of items. A Lisp macro can be provided which takes care of this situation. The implementation below handles the underflow in one deque piece by transferring about one half of the elements from the opposite piece. This keeps the amortized cost for pushes and pops O(1), and prevents the degenerate behavior of bouncing all the elements from one side to the other when pops are requested which alternate between the two ends of the deque.
 
<langsyntaxhighlight lang="lisp">
;;; Obtained from Usenet,
;;; Message-ID: <b3b1cc90-2e2b-43c3-b7d9-785ae29870e7@e23g2000prf.googlegroups.com>
Line 736 ⟶ 780:
,other-piece ,new-other)
,result)))
</syntaxhighlight>
</lang>
 
Demo:
Line 780 ⟶ 824:
 
D has static arrays.
<langsyntaxhighlight lang="d">int[3] array;
array[0] = 5;
// array.length = 4; // compile-time error</langsyntaxhighlight>
 
D has dynamic arrays.
<langsyntaxhighlight lang="d">int[] array;
array ~= 5; // append 5
array.length = 3;
array[3] = 17; // runtime error: out of bounds. check removed in release mode.
array = [2, 17, 3];
writefln(array.sort); // 2, 3, 17</langsyntaxhighlight>
 
D has associative arrays.
<langsyntaxhighlight lang="d">int[int] array;
// array ~= 5; // it doesn't work that way!
array[5] = 17;
Line 800 ⟶ 844:
writefln(array.keys, " -> ", array.values);
assert(5 in array); // returns a pointer, by the way
if (auto ptr = 6 in array) writefln(*ptr); // 20</langsyntaxhighlight>
=={{header|Delphi}}==
 
===Arrays===
Arrays are collection of values with memory self managed, can be static (size fixed and index not need start in zero) or dynamic (size scaled by user in run time and away start index in zero).
<syntaxhighlight lang="delphi">
<lang Delphi>
// Creates and initializes a new integer Array
var
Line 836 ⟶ 880:
var intArray7: TArray<Integer> := [1, 2, 3];
end;
</syntaxhighlight>
</lang>
===List===
Lists are objects and need be release from memory after use.
<syntaxhighlight lang="delphi">
<lang Delphi>
var
// TLists can't be initialized or created in declaration scope
Line 868 ⟶ 912:
List4.free;
end;
</syntaxhighlight>
</lang>
 
===Dictionary===
TDictionary is a generic class.It represents a collection of key/value pairs. Keys must be unique.
It need be release from memory after use.
<syntaxhighlight lang="delphi">
<lang Delphi>
var
// TDictionary can't be initialized or created in declaration scope
Line 892 ⟶ 936:
Dic3.free;
end;
</syntaxhighlight>
</lang>
===Queue===
TQueue is a generic class.It represents a collection of data, stored in fist-in fist-out mode.
It need be release from memory after use.
<syntaxhighlight lang="delphi">
<lang Delphi>
var
Queue1, Queue2: TQueue<Integer>;
Line 921 ⟶ 965:
Queue3.free;
end;
</syntaxhighlight>
</lang>
===Stack===
TStack is a generic class.It represents a collection of data, stored in last-in first-out mode.
It need be release from memory after use.
<syntaxhighlight lang="delphi">
<lang Delphi>
var
Stack1, Stack2: TStack<Integer>;
Line 950 ⟶ 994:
Stack3.free;
end;
</syntaxhighlight>
</lang>
===Strings===
String are array of chars, start index is one (not zero like almost languages).
Can store ansichar (one byte char) or widechar (two bytes char), the default for newer versions is widestring;
<syntaxhighlight lang="delphi">
<lang Delphi>
var
Str1:String; // default WideString
Line 982 ⟶ 1,026:
Writeln(Str1[length(str1)]); // the same above
end;
</syntaxhighlight>
</lang>
See [[#Pascal]] for more info.
=={{header|Diego}}==
Diego operates in the real and abstract world. In the real world, collections exist as scalars, vectors, abilities, specifications, inventories, and, non-fungible tokens:
<syntaxhighlight lang="diego">use_namespace(rosettacode)_me();
 
// Real world collections
with_route(wp1-wp2)_scalar(wp1wp2Distance)_distan({m},32); // simple distance scalar
 
// Three dimensional vector (displacement - orientation (via quaternion) - energy consumption)
with_route(from-wp1-to-wp2)_vector(wp1Towp2Displacement)_distan({m},32)_orientatout(0.98,0.174i,0.044j,0.087k)_ergconsump({kJ},35.483);
 
with_robot(alif)_sensor(frontCamera)_type(camera_3d);
with_robot(alif)_abilit(frontalVision)_of[frontCamera]; // ability (1-dimensional)
with_robot(alif)_sensor(rearCamera)_type(camera_3d);
with_robot(alif)_spec(vision)_of([frontCamera],[rearCamera]); // specification (2-dimensional)
 
// Inventory of wheels of robot 'alif'
with_robot(alif)_invent(wheels)_compon(frontLeftWheel, frontRightWheel, rearLeftWheel, rearRightWheel)_type(wheel);
 
// Non-fungible token (blockchained) of robot photo (default ledger)
with_robot(beh)_camera(frontCamera)_snap(74827222-32232-22)
add_nft()_[]_chain(block);
;
 
// Non-fungible token (crosschained) of robot photo (default ledger)
with_robot(beh)_camera(frontCamera)_snap(74827222-32232-42)
add_nft()_[]_chain(cross);
;
 
reset_ns[];</syntaxhighlight>
 
In the abstract world, collections exist as variables, stacks, queues, arrays, matricies, clumps, lists, dictionaries, and, hashes:
<syntaxhighlight lang="diego">use_namespace(rosettacode)_me();
 
// Abstract world collections
add_var({int},wp1wp2Distance)_value(32); // variable
add_stack({int},intStack)_values(1,2,3,6,7,9); // stack
add_queue({double},intStack)_values(0.03,0.04,0.05,0.06,0.07,0.08); // queue
add_ary({str},citrusFruit)_values(lime,orange,lemon); // array
add_matrix()_subs(4,4)_identity(); // simple identity matrix
 
// rotation matrix
add_matrix(wp1Towp2DisplacementRotationMatrix)_row(0.981,-0.155,0.116)_row(0.186,0.924,-0.333)_row(-0.055,0.349,0.936);
 
add_clump()_subs(5,3,2,1); // simple clump (zero'ed)
 
// list (of robots) from abstract robot objects
add_list({robot},robots)_values([alif],[bah],[tah],[thah],[jim]);
 
// list (of robots) from SQL query
add_list({robot},robots)_sql(SELECT id, name, type FROM tbl_robot)_as(dba_admin);
 
// dictionary
add_dict(tanzanianBanknoteWidths)_keys(500,1000,2000,5000,10000)_values(120,125,130,135,140);
 
// hash of two images loaded from URIs
add_hash()_ary()_values()_img()_load(/img_027454322.jpg)_img()_load(/img_027454323.jpg);
 
reset_ns[];</syntaxhighlight>
 
=={{header|E}}==
 
E has both mutable and immutable builtin collections; the common types are list (array), map (hash table), and set (hash table). This interactive session shows mutable lists and immutable collections of all three types. See also [[Arrays#E]].
 
<langsyntaxhighlight lang="e">? def constList := [1,2,3,4,5]
# value: [1, 2, 3, 4, 5]
 
Line 1,014 ⟶ 1,117:
 
? constSet.contains(3)
# value: true</langsyntaxhighlight>
 
=={{header|EasyLang}}==
EasyLang only has an array as the type of collection. Arrays can be put inside of arrays. All arrays are mutable.
<syntaxhighlight lang="easylang">
array[] &= 1
array[] &= 2
array[] &= 3
arrayArray[][] &= [ 1 2 ]
arrayArray[][] &= [ 3 4 ]
arrayArray[][] &= [ 5 6 ]
print array[]
print arrayArray[][]
</syntaxhighlight>
{{out}}
<pre>
[ 1 2 3 ]
[
[ 1 2 ]
[ 3 4 ]
[ 5 6 ]
]
</pre>
 
=={{header|EchoLisp}}==
The collection will be a list, which is not unusual in EchoLisp. We add items - symbols - to the collection, and save it to local storage.
<langsyntaxhighlight lang="lisp">
(define my-collection ' ( 🌱 ☀️ ☔️ ))
(set! my-collection (cons '🎥 my-collection))
Line 1,028 ⟶ 1,153:
(local-put 'my-collection)
→ my-collection
</syntaxhighlight>
</lang>
 
=={{header|Elena}}==
ELENA 5.0:
===Arrays===
<langsyntaxhighlight lang="elena">
// Weak array
var stringArr := Array.allocate(5);
Line 1,040 ⟶ 1,165:
// initialized array
var intArray := new int[]{1, 2, 3, 4, 5};
</syntaxhighlight>
</lang>
 
===ArrayList and List===
<langsyntaxhighlight lang="elena">
//Create and initialize ArrayList
var myAl := new system'collections'ArrayList().append:("Hello").append:("World").append:("!");
//Create and initialize List
var myList := new system'collections'List().append:("Hello").append:("World").append:("!");
</syntaxhighlight>
</lang>
 
===Dictionary===
<langsyntaxhighlight lang="elena">
//Create a dictionary
var dict := system'collections'Dictionary.new();
dict["Hello"] := "World";
dict["Key"] := "Value";
</syntaxhighlight>
</lang>
 
=={{header|Elixir}}==
Line 1,066 ⟶ 1,191:
===List===
Elixir uses square brackets to specify a list of values. Values can be of any type:
<langsyntaxhighlight lang="elixir">empty_list = []
list = [1,2,3,4,5]
length(list) #=> 5
Line 1,074 ⟶ 1,199:
Enum.at(list,3) #=> 4
list ++ [6,7] #=> [1,2,3,4,5,6,7]
list -- [4,2] #=> [1,3,5]</langsyntaxhighlight>
 
===Tuple===
Elixir uses curly brackets to define tuples. Like lists, tuples can hold any value:
Tuples store elements contiguously in memory. This means accessing a tuple element per index or getting the tuple size is a fast operation:
<langsyntaxhighlight lang="elixir">empty_tuple = {} #=> {}
tuple = {0,1,2,3,4} #=> {0, 1, 2, 3, 4}
tuple_size(tuple) #=> 5
elem(tuple, 2) #=> 2
put_elem(tuple,3,:atom) #=> {0, 1, 2, :atom, 4}</langsyntaxhighlight>
 
===Keyword lists===
In Elixir, when we have a list of tuples and the first item of the tuple (i.e. the key) is an atom, we call it a keyword list:
<langsyntaxhighlight lang="elixir">list = [{:a,1},{:b,2}] #=> [a: 1, b: 2]
list == [a: 1, b: 2] #=> true
list[:a] #=> 1
list ++ [c: 3, a: 5] #=> [a: 1, b: 2, c: 3, a: 5]</langsyntaxhighlight>
Keyword lists are important because they have two special characteristics:
# They keep the keys ordered, as specified by the developer.
Line 1,100 ⟶ 1,225:
# Maps allow any value as a key.
# Maps' keys do not follow any ordering.
<langsyntaxhighlight lang="elixir">empty_map = Map.new #=> %{}
kwlist = [x: 1, y: 2] # Key Word List
Map.new(kwlist) #=> %{x: 1, y: 2}
Line 1,114 ⟶ 1,239:
map = %{:a => 1, :b => 2} #=> %{a: 1, b: 2}
map.a #=> 1
%{map | :a => 2} #=> %{a: 2, b: 2} update only</langsyntaxhighlight>
 
===Set===
<langsyntaxhighlight lang="elixir">empty_set = MapSet.new #=> #MapSet<[]>
set1 = MapSet.new(1..4) #=> #MapSet<[1, 2, 3, 4]>
MapSet.size(set1) #=> 4
Line 1,126 ⟶ 1,251:
MapSet.intersection(set1,set2) #=> #MapSet<[2, 4]>
MapSet.difference(set1,set2) #=> #MapSet<[1, 3]>
MapSet.subset?(set1,set2) #=> false</langsyntaxhighlight>
 
===Struct===
Structs are extensions built on top of maps that provide compile-time checks and default values.
<langsyntaxhighlight lang="elixir">defmodule User do
defstruct name: "john", age: 27
end
Line 1,138 ⟶ 1,263:
age #=> 27
meg = %User{name: "meg"} #=> %User{age: 27, name: "meg"}
is_map(meg) #=> true</langsyntaxhighlight>
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">USING: assocs deques dlists lists lists.lazy sequences sets ;
 
! ===fixed-size sequences===
Line 1,209 ⟶ 1,334:
 
! Factor also comes with disjoint sets, interval maps, heaps,
! boxes, directed graphs, locked I/O buffers, trees, and more!</langsyntaxhighlight>
 
=={{header|Fancy}}==
Line 1,215 ⟶ 1,340:
===array===
 
<langsyntaxhighlight lang="fancy">
# creating an empty array and adding values
 
Line 1,224 ⟶ 1,349:
# creating an array with the constructor
a = Array new # => []
</syntaxhighlight>
</lang>
 
===hash===
 
<langsyntaxhighlight lang="fancy"># creating an empty hash
 
h = <[]> # => <[]>
Line 1,237 ⟶ 1,362:
# creating a hash with the constructor
h = Hash new # => <[]>
</syntaxhighlight>
</lang>
 
=={{header|Forth}}==
Line 1,244 ⟶ 1,369:
===Array===
 
<langsyntaxhighlight lang="forth">include ffl/car.fs
 
10 car-create ar \ create a dynamic array with initial size 10
Line 1,251 ⟶ 1,376:
3 1 ar car-set \ ar[1] = 3
1 0 ar car-insert \ ar[0] = 1 ar[1] = 2 ar[2] = 3
</syntaxhighlight>
</lang>
 
===Double linked list===
 
<langsyntaxhighlight lang="forth">include ffl/dcl.fs
 
dcl-create dl \ create a double linked list
Line 1,262 ⟶ 1,387:
1 dl dcl-prepend
2 1 dl dcl-insert \ dl[0] = 1 dl[1] = 2 dl[2] = 3
</syntaxhighlight>
</lang>
 
===Hashtable===
 
<langsyntaxhighlight lang="forth">include ffl/hct.fs
 
10 hct-create ht \ create a hashtable with initial size 10
Line 1,273 ⟶ 1,398:
2 s" two" ht hct-insert \ ht["two"] = 2
3 s" three" ht hct-insert \ ht["three"] = 3
</syntaxhighlight>
</lang>
 
=={{header|Fortran}}==
===Standard===
The only facility for a collection more organised than a collection of separately-named variables (even if with a system for the names) is the array, which is a collection of items of identical type, indexed by an integer only, definitely not by a text as in say Snobol. Thus <langsyntaxhighlight Fortranlang="fortran"> REAL A(36) !Declares a one-dimensional array A(1), A(2), ... A(36)
A(1) = 1 !Assigns a value to the first element.
A(2) = 3*A(1) + 5 !The second element gets 8.</langsyntaxhighlight>
With F90 came a large expansion in the facilities for manipulating arrays. They can now have any lower bound, as in <code>REAL A(-6:+12)</code> and their size can be defined at run time, not just compile time. Further, programmer-defined data aggregates can be defined via the TYPE statement, and arrays of such types can be manipulated. However, type-matching remains rigid: all elements of an array must be of the same type. So, <langsyntaxhighlight Fortranlang="fortran"> TYPE(MIXED) !Name the "type".
INTEGER COUNTER !Its content is listed.
REAL WEIGHT,DEPTH
Line 1,286 ⟶ 1,411:
COMPLEX PATH(6) !The mixed collection includes an array.
END TYPE MIXED
TYPE(MIXED) TEMP,A(6) !Declare some items of that type.</langsyntaxhighlight>
would define a collection of variables constituting a "type", then a simple variable TEMP whose parts would be accessed via the likes of <code>TEMP.DEPTH</code> or <code>TEMP%DEPTH</code>, and an array of such aggregates where <code> A(3).PATH(1) = (2.7,3.1)</code> assigns a complex number to the first step of the PATH of the third element of array A. The indexing must be associated with the item having an array aspect, but in pl/i <code>A.PATH(3,1)</code> - or other groupings - would be acceptable.
 
Line 1,299 ⟶ 1,424:
 
This can be fixed size or dynamic, have arbitrary lower and upper bounds, have up to 8 dimensions and any kind of element type (including user defined types). Here are some simple examples:
<langsyntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
'create fixed size array of integers
Line 1,315 ⟶ 1,440:
Dim c(1 To 2, 1 To 2) As Byte = {{1, 2}, {3, 4}}
Print c(1, 1), c(2,2)
Sleep </langsyntaxhighlight>
 
{{out}}
Line 1,322 ⟶ 1,447:
3.5 7.1
1 4
</pre>
 
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">
include "NSLog.incl"
 
void local fn Array
CFArrayRef array = @[@"Alpha",@"Bravo",@"Charlie",@"Delta"]
NSLog(@"Array:%@\n",array)
end fn
 
void local fn Dictionary
CFDictionaryRef dict = @{@"Key1":@"Value1",@"Key2":@"Value2",@"Key3":@"Value3"}
NSLog(@"Dictionary:%@\n",dict)
end fn
 
void local fn Set
CFSetRef set = fn SetWithArray( @[@"Echo",@"Echo",@"FutureBasic",@"Golf",@"Hotel",@"India"] )
NSLog(@"Set:%@\n",set)
end fn
 
void local fn IndexPath
long indexes(3)
indexes(0) = 1 : indexes(1) = 4 : indexes(2) = 3 : indexes(3) = 2
IndexPathRef indexPath = fn IndexPathWithIndexes( @indexes(0), 4 )
NSLog(@"IndexPath:%@\n",indexPath)
end fn
 
void local fn IndexSet
IndexSetRef indexSet = fn IndexSetWithIndexesInRange( fn CFRangeMake( 12, 5 ) )
NSLog(@"IndexSet:%@\n",indexSet)
end fn
 
void local fn CountedSet
CountedSetRef countedSet = fn CountedSetWithArray( @[@"Juliet",@"Lima",@"Mike",@"Lima",@"Kilo",@"Lima",@"Juliet",@"Mike",@"Lima"] )
NSLog(@"CountedSet:%@\n",countedSet)
end fn
 
void local fn OrderedSet
OrderedSetRef orderedSet = fn OrderedSetWithObjects( @"November", @"Oscar", @"Papa", NULL )
NSLog(@"OrderedSet:%@\n",orderedSet)
end fn
 
fn Array
fn Dictionary
fn Set
fn IndexPath
fn IndexSet
fn CountedSet
fn OrderedSet
 
HandleEvents
</syntaxhighlight>
 
{{out}}
<pre>
Array:(
Alpha,
Bravo,
Charlie,
Delta
)
 
Dictionary:{
Key1 = Value1;
Key2 = Value2;
Key3 = Value3;
}
 
Set:{(
India,
Echo,
Hotel,
FutureBasic,
Golf
)}
 
IndexPath:<NSIndexPath: 0x93855b96cef033ba> {length = 4, path = 1 - 4 - 3 - 2}
 
IndexSet:<NSIndexSet: 0x600000318cc0>[number of indexes: 5 (in 1 ranges), indexes: (12-16)]
 
CountedSet:<NSCountedSet: 0x60000031aa60> (Mike [2], Lima [4], Juliet [2], Kilo [1])
 
OrderedSet:{(
November,
Oscar,
Papa
)}
</pre>
 
=={{header|Gambas}}==
'''[https://gambas-playground.proko.eu/?gist=004236066581dd85f39f34e100bf5c40 Click this link to run this code]'''
<langsyntaxhighlight lang="gambas">Public Sub Main()
Dim siCount As Short
Dim cCollection As Collection = ["0": "zero", "1": "one", "2": "two", "3": "three", "4": "four",
Line 1,335 ⟶ 1,548:
Next
 
End</langsyntaxhighlight>
Output:
<pre>
Line 1,355 ⟶ 1,568:
* Maps
Built in resizable collections are slices and maps. The value type for these collections can be any Go type, including interface. An empty interface can reference an object of any type, providing a kind of polymorphic collection. Here the variable <tt>a</tt> is a slice of interface{} objects.
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 1,364 ⟶ 1,577:
a = append(a, "apples", "oranges")
fmt.Println(a)
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,381 ⟶ 1,594:
=={{header|Groovy}}==
Lists are just variable-length, integer-indexed arrays.
<langsyntaxhighlight lang="groovy">def emptyList = []
assert emptyList.isEmpty() : "These are not the items you're looking for"
assert emptyList.size() == 0 : "Empty list has size 0"
Line 1,401 ⟶ 1,614:
["even more stuff", "even more stuff", "more stuff"] \
: "reverse referencing last 3 elements"
println ([combinedList: combinedList])</langsyntaxhighlight>
 
{{out}}
Line 1,407 ⟶ 1,620:
 
Maps are just variable-length, associative arrays. They are not necessarily order preserving.
<langsyntaxhighlight lang="groovy">def emptyMap = [:]
assert emptyMap.isEmpty() : "These are not the items you're looking for"
assert emptyMap.size() == 0 : "Empty map has size 0"
Line 1,430 ⟶ 1,643:
assert combinedMap.keySet().containsAll(
["lastName", "count", "eyes", "hair", "weight", "initial", "firstName", "birthdate"])
println ([combinedMap: combinedMap])</langsyntaxhighlight>
 
{{out}}
Line 1,436 ⟶ 1,649:
 
Sets are unique, not indexed at all (contents can only be discovered by traversal), and are not necessarily order preserving. There is no particular special language support for denoting a Set, although a Set may be initialized from a List, and Sets share many of the same operations and methods that are available in Lists.
<langsyntaxhighlight lang="groovy">def emptySet = new HashSet()
assert emptySet.isEmpty() : "These are not the items you're looking for"
assert emptySet.size() == 0 : "Empty set has size 0"
Line 1,451 ⟶ 1,664:
combinedSet << "even more stuff"
assert combinedSet.size() == 5 : "No duplicate elements allowed!"
println ([combinedSet: combinedSet])</langsyntaxhighlight>
 
{{out}}
Line 1,460 ⟶ 1,673:
The list is typically the first collection type to be encountered in textbooks, but other types may tend to be more efficient, or more flexibly accessed; see the <code>Data</code> hierarchy of [http://www.haskell.org/ghc/docs/latest/html/libraries/ GHC's standard library]. New collection types may be defined with <code>data</code>.
 
<langsyntaxhighlight lang="haskell">[1, 2, 3, 4, 5]</langsyntaxhighlight>
 
To prepend a single element to a list, use the <code>:</code> operator:
 
<langsyntaxhighlight lang="haskell">1 : [2, 3, 4]</langsyntaxhighlight>
 
To concatenate two lists, use <code>++</code>:
 
<langsyntaxhighlight lang="haskell">[1, 2] ++ [3, 4]</langsyntaxhighlight>
 
To concatenate a whole list of lists, use <code>concat</code>:
 
<langsyntaxhighlight lang="haskell">concat [[1, 2], [3, 4], [5, 6, 7]]</langsyntaxhighlight>
 
===Data.Array===
Faster retrieval by index:
<langsyntaxhighlight lang="haskell">import Data.Array (Array, listArray, Ix, (!))
 
triples :: Array Int (Char, String, String)
Line 1,494 ⟶ 1,707:
 
main :: IO ()
main = (putStrLn . unlines) $ indexedItem triples <$> [2, 4, 6]</langsyntaxhighlight>
{{Out}}
<pre>虎 hǔ tiger
Line 1,502 ⟶ 1,715:
===Data.Map===
Flexible key-value indexing and efficient retrieval:
<langsyntaxhighlight lang="haskell">import qualified Data.Map as M
import Data.Maybe (isJust)
 
Line 1,521 ⟶ 1,734:
main :: IO ()
main =
print $ sequence $ filter isJust (maybeValue <$> ["beta", "delta", "zeta"])</langsyntaxhighlight>
{{Out}}
<pre>Just [2,4,6]</pre>
Line 1,527 ⟶ 1,740:
===Data.Set===
Repertoire of efficient set operations:
<langsyntaxhighlight lang="haskell">import qualified Data.Set as S
 
setA :: S.Set String
Line 1,536 ⟶ 1,749:
 
main :: IO ()
main = (print . S.toList) (S.intersection setA setB)</langsyntaxhighlight>
{{Out}}
<pre>["delta","epsilon"]</pre>
Line 1,544 ⟶ 1,757:
 
Several data types could be considered collections:
<langsyntaxhighlight Iconlang="icon"># Creation of collections:
s := "abccd" # string, an ordered collection of characters, immutable
c := 'abcd' # cset, an unordered collection of characters, immutable
Line 1,551 ⟶ 1,764:
L := [] # list, an ordered collection of values indexed by position 1..n or as stack/queue, mutable, contents may be of any type
record constructorname(field1,field2,fieldetc) # record, a collection of values stored in named fields, mutable, contents may be of any type (declare outside procedures)
R := constructorname() # record (creation)</langsyntaxhighlight>
 
Adding to these collections can be accomplished as follows:
<syntaxhighlight lang="icon">
<lang Icon>
s ||:= "xyz" # concatenation
c ++:= 'xyz' # union
Line 1,560 ⟶ 1,773:
T["abc"] := "xyz" # insert create/overwrite
put(L,1) # put (extend), also push
R.field1 := "xyz" # overwrite</langsyntaxhighlight>
 
Additionally, the following operations apply:
<syntaxhighlight lang="icon">
<lang Icon>
S := S ++ S2 # union of two sets or two csets
S ++:= S2 # augmented assignment
L := L ||| L2 # list concatenation
L |||:= L2 # augmented assignment</langsyntaxhighlight>
 
=={{header|J}}==
Line 1,574 ⟶ 1,787:
J will, when possible without losing significance of the original value, implicitly convert values to a type which allows them represented in a homogeneous fashion in a collection. Heterogeneous collections are possible via "boxing" (analogous to a "variant" data type).
 
<langsyntaxhighlight lang="j"> c =: 0 10 20 30 40 NB. A collection
c, 50 NB. Append 50 to the collection
Line 1,660 ⟶ 1,873:
1 1 1 1 1
c -: 10 i.5 NB. Test for identicality
1</langsyntaxhighlight>
 
=={{header|Jakt}}==
===Array===
In Jakt, arrays are of variable size.
<syntaxhighlight lang="jakt">
fn main() {
mut array: [String] = []
array.push("Apple")
array.push("Banana")
println("{}", array)
}
</syntaxhighlight>
 
===Set===
<syntaxhighlight lang="jakt">
fn main() {
mut set: {String} = {}
set.add("Apple")
set.add("Banana")
println("{}", set)
}
</syntaxhighlight>
 
===Dictionary===
<syntaxhighlight lang="jakt">
fn main() {
mut dictionary: [i64:String] = [:]
dictionary[1] = "Apple"
dictionary[2] = "Banana"
println("{}", dictionary)
}
</syntaxhighlight>
 
 
=={{header|Java}}==
Line 1,668 ⟶ 1,914:
When creating a List of any kind in Java (Arraylist or LinkedList), the type of the variable is a style choice. It is sometimes considered good practice to make the pointer of type List and the new object of a List subclass. Doing this will ensure two things: if you need to change the type of list you want you only need to change one line and all of your methods will still work, and you will not be able to use any methods that are specific to the List type you chose. So in this example, all instances of "ArrayList" can be changed to "LinkedList" and it will still work, but you will not be able to use a method like "ensureCapactiy()" because the variable is of type List.
 
<langsyntaxhighlight Java5lang="java5">List arrayList = new ArrayList();
arrayList.add(new Integer(0));
// alternative with primitive autoboxed to an Integer object automatically
Line 1,681 ⟶ 1,927:
for(int i = 0; i < 10; i++) {
myarrlist.add(i);
}</langsyntaxhighlight>
 
<langsyntaxhighlight Java5lang="java5">//loop through myarrlist to sum each entry
for ( i = 0; i < myarrlist.size(); i++) {
sum += myarrlist.get(i);
}</langsyntaxhighlight>
or
<langsyntaxhighlight Java5lang="java5">for(int i : myarrlist) {
sum += i;
}</langsyntaxhighlight>
 
<langsyntaxhighlight Java5lang="java5">//remove the last entry in the ArrayList
myarrlist.remove(myarrlist.size()-1)
 
//clear the ArrayList
myarrlist.clear();</langsyntaxhighlight>
Here is a reference table for characteristics of commonly used <code>Collections</code> classes:
{|class="wikitable"
Line 1,740 ⟶ 1,986:
|}
=== Using the Scala collection classes===
The [[Scala|Scala]] libraries are valid Java byte-code libraries. The collection part of these are rich because the multiple inheritance by traits. E.g. an [http://www.scala-lang.org/api/current/index.html#scala.collection.mutable.ArrayBuffer ArrayBuffer] has properties inherent of 9 traits such as Buffer[A], IndexedSeqOptimized[A, ArrayBuffer[A]], Builder[A, ArrayBuffer[A]], ResizableArray[A] and Serializable. Another collection e.g. TrieMap uses some of these and other added traits. A [http://www.scala-lang.org/api/current/index.html#scala.collection.concurrent.TrieMap TrieMap] -a hashmap- is the most advanced of all. It supports parallel processing without blocking.<langsyntaxhighlight Java5lang="java5">import scala.Tuple2;
import scala.collection.concurrent.TrieMap;
import scala.collection.immutable.HashSet;
Line 1,790 ⟶ 2,036:
}
}
</syntaxhighlight>
</lang>
 
=={{header|JavaScript}}==
<langsyntaxhighlight lang="javascript">var array = [];
array.push('abc');
array.push(123);
array.push(new MyClass);
console.log( array[2] );</langsyntaxhighlight>
 
<langsyntaxhighlight lang="javascript">var obj = {};
obj['foo'] = 'xyz'; //equivalent to: obj.foo = 'xyz';
obj['bar'] = new MyClass; //equivalent to: obj.bar = new MyClass;
obj['1x; ~~:-b'] = 'text'; //no equivalent
console.log(obj['1x; ~~:-b']);</langsyntaxhighlight>
 
=={{header|jq}}==
Line 1,816 ⟶ 2,062:
One of the programmatic approaches to creating JSON objects allows
the key names to be specified as unquoted strings, e.g.
<langsyntaxhighlight lang="jq">{"a": 1} == {a: 1}</langsyntaxhighlight>
 
evaluates to true. Variables can also be used, e.g. the object {"a":1} can also be created by the following
pipeline:
<langsyntaxhighlight lang="jq">"a" as $key | 1 as $value | {($key): $value}</langsyntaxhighlight>
 
===Equality===
Line 1,834 ⟶ 2,080:
modifying an element of a composite structure. For example, consider the following pipeline:
 
<langsyntaxhighlight lang="jq">[0,1,2] | .[0] = 10</langsyntaxhighlight>
 
The result (or output) of this sequence is [10,1,2], so it is convenient to
Line 1,842 ⟶ 2,088:
Julia has a wide variety of collections, including vectors, matrices, lists of Any data type, associative arrays, and bitsets.
There is a slicing notation and list comprehensions similar to those in Python, but the base index is by default 1, not 0. In Julia, a collection is a just variable length array:
<langsyntaxhighlight lang="julia">
 
julia> collection = []
Line 1,853 ⟶ 2,099:
4
7
</syntaxhighlight>
</lang>
 
=={{header|Kotlin}}==
Line 1,859 ⟶ 2,105:
 
In addition, Kotlin can also access other types of Java collection such as LinkedList, Queue, Deque and Stack by simply importing the appropriate type:
<langsyntaxhighlight lang="scala">import java.util.PriorityQueue
 
fun main(args: Array<String>) {
Line 1,901 ⟶ 2,147:
pq.add("First"); pq.add("Second"); pq.add("Third")
println(pq)
}</langsyntaxhighlight>
 
{{out}}
Line 1,918 ⟶ 2,164:
=={{header|Lingo}}==
Lingo has 2 collection types: lists (arrays) and property lists (hashes):
<langsyntaxhighlight lang="lingo">-- list stuff
l = [1, 2]
l.add(3)
Line 1,930 ⟶ 2,176:
pl["barfoo"] = 4
put pl
-- [#foo: 1, #bar: 2, #foobar: 3, "barfoo": 4]</langsyntaxhighlight>
 
Lingo is not statically-typed, but if needed, a collection type that only accepts a specific data type can be created by sub-classing one of the 2 available collection types and overwriting its access methods, so that those block any data type other than the one that was passed to the constructor.
Line 1,936 ⟶ 2,182:
=={{header|Lisaac}}==
===vector===
<langsyntaxhighlight Lisaaclang="lisaac">+ vector : ARRAY[INTEGER];
vector := ARRAY[INTEGER].create_with_capacity 32 lower 0;
vector.add_last 1;
vector.add_last 2;</langsyntaxhighlight>
===hashed set===
<langsyntaxhighlight Lisaaclang="lisaac">+ set : HASHED_SET[INTEGER];
set := HASHED_SET[INTEGER].create;
set.add 1;
set.add 2;</langsyntaxhighlight>
===linked list===
<langsyntaxhighlight Lisaaclang="lisaac">+ list : LINKED_LIST[INTEGER];
list := LINKED_LIST[INTEGER].create;
list.add_last 1;
list.add_last 2;</langsyntaxhighlight>
===hashed dictionary===
<langsyntaxhighlight Lisaaclang="lisaac">+ dict : HASHED_DICTIONARY[INTEGER/*value*/, STRING_CONSTANT/*key*/];
dict := HASHED_DICTIONARY[INTEGER, STRING_CONSTANT].create;
dict.put 1 to "one";
dict.put 2 to "two";</langsyntaxhighlight>
 
=={{header|Logo}}==
Line 1,965 ⟶ 2,211:
Lua has only one type of collection, the table. But Lua's table has features of both, traditional arrays and hash maps (dictionaries). You can even mix both within one table. Note, that the numeric indices of Lua's table start at 1, not at 0 as with most other languages.
 
<langsyntaxhighlight lang="lua">collection = {0, '1'}
print(collection[1]) -- prints 0
 
Line 1,972 ⟶ 2,218:
print(collection.foo) -- syntactic sugar, also prints 0
 
collection = {0, '1', ["foo"] = 0, ["bar"] = '1'}</langsyntaxhighlight>
 
It is idiomatic in Lua to represent a Set data structure with a table of keys to the true value.
Line 1,978 ⟶ 2,224:
=={{header|M2000 Interpreter}}==
===Ordered List (array)===
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module Arr {
\\ array as tuple
Line 1,993 ⟶ 2,239:
}
Arr
</syntaxhighlight>
</lang>
===Ordered List (stack)===
A stack may have values inventories,arrays, stacks, groups
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module CheckStack {
\\ ordered collection: Stack
Line 2,033 ⟶ 2,279:
}
CheckStack
</syntaxhighlight>
</lang>
===Inventories as Maps===
An Inventory may have values inventories,arrays, stacks, groups
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module Maps {
\\ Inventory as pairs of keys/values
Line 2,065 ⟶ 2,311:
}
Maps
</syntaxhighlight>
</lang>
 
===Inventories as Sets===
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module Sets {
\\ Inventory as set of keys
Line 2,100 ⟶ 2,346:
}
Sets
</syntaxhighlight>
</lang>
 
===Using a Visual Basic 6 Collection===
Line 2,106 ⟶ 2,352:
 
We can get a list
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module GetC {
declare c collection
Line 2,157 ⟶ 2,403:
Read a
Print type$(a)="Collection" ' if we don't declare
</syntaxhighlight>
</lang>
{Out}
<pre>
Line 2,185 ⟶ 2,431:
=={{header|Maple}}==
Defining lists:
<syntaxhighlight lang="maple">
<lang Maple>
L1 := [3, 4, 5, 6];
L1 := [3, 4, 5, 6]
Line 2,191 ⟶ 2,437:
L2 := [7, 8, 9];
L2 := [7, 8, 9]
</syntaxhighlight>
</lang>
Concatenating two lists:
<syntaxhighlight lang="maple">
<lang Maple>
[op(L1), op(L2)]
[3, 4, 5, 6, 7, 8, 9]
</syntaxhighlight>
</lang>
 
Defining an Array:
<syntaxhighlight lang="maple">
<lang Maple>
A1 := Array([3, 4, 5, 6]);
A1 := [3, 4, 5, 6]
</syntaxhighlight>
</lang>
 
Appending to a Vector:
<syntaxhighlight lang="maple">
<lang Maple>
ArrayTools:-Append(A1, 7);
A1 := [3, 4, 5, 6, 7]
</syntaxhighlight>
</lang>
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">Lst = {3, 4, 5, 6}
->{3, 4, 5, 6}
 
Line 2,223 ⟶ 2,469:
 
Insert[ Lst, X, 4]
->{1, 2, 3, X, 4, 5, 6}</langsyntaxhighlight>
 
=={{header|MATLAB}} / {{header|Octave}}==
Line 2,229 ⟶ 2,475:
 
Sample Usage:
<langsyntaxhighlight MATLABlang="matlab">>> A = {2,'TPS Report'} %Declare cell-array and initialize
 
A =
Line 2,252 ⟶ 2,498:
 
make: 'honda'
year: 2003</langsyntaxhighlight>
'''Bold text'''
 
=={{header|MiniScript}}==
MiniScript supports both lists and maps (dictionaries). This task demonstrates lists.
<langsyntaxhighlight MiniScriptlang="miniscript">seq = [0, "foo", pi]
seq.push 42
seq = seq + [1, 2, 3]
print seq</langsyntaxhighlight>
 
{{output}}
Line 2,267 ⟶ 2,513:
=={{header|MS SmallBasic}}==
Only with LD extension
<syntaxhighlight lang="mssmallbasic">
<lang MSsmallbasic>
ll=LDList.CreateFromValues("")
LDList.Add(ll "Cars")
LDList.Add(ll "Toys")
LDList.Print(ll)
</syntaxhighlight>
</lang>
result:
 
Line 2,283 ⟶ 2,529:
=={{header|NetRexx}}==
NetRexx can take advantage of Java's <tt>Collection</tt> classes. This example uses the <tt>Set</tt> interface backed by a <tt>HashSet</tt>:
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref symbols nobinary
 
Line 2,299 ⟶ 2,545:
 
return
</syntaxhighlight>
</lang>
 
=={{header|Nim}}==
===Array===
Length is known at compile time
<langsyntaxhighlight lang="nim">var a = [1,2,3,4,5,6,7,8,9]
var b: array[128, int]
b[9] = 10
b[0..8] = a
var c: array['a'..'d', float] = [1.0, 1.1, 1.2, 1.3]
c['b'] = 10000</langsyntaxhighlight>
 
===Seq===
Variable length sequences
<langsyntaxhighlight lang="nim">var d = @[1,2,3,5,6,7,8,9]
d.add(10)
d.add([11,12,13,14])
Line 2,323 ⟶ 2,569:
var f = newSeq[string]()
f.add("foo")
f.add("bar")</langsyntaxhighlight>
 
===Tuple===
Fixed length, named
<langsyntaxhighlight lang="nim">var g = (13, 13, 14)
g[0] = 12
 
Line 2,333 ⟶ 2,579:
 
# A sequence of key-val tuples:
var i = {"foo": 12, "bar": 13}</langsyntaxhighlight>
 
===Set===
Bit vector of ordinals
<langsyntaxhighlight lang="nim">var j: set[char]
j.incl('X')
 
var k = {'a'..'z', '0'..'9'}
 
j = j + k</langsyntaxhighlight>
 
===Tables===
Hash tables (there are also ordered hash tables and counting hash tables)
<langsyntaxhighlight lang="nim">import tables
var l = initTable[string, int]()
l["foo"] = 12
Line 2,352 ⟶ 2,598:
 
var m = {"foo": 12, "bar": 13}.toTable
m["baz"] = 14</langsyntaxhighlight>
 
===Sets===
Hash sets (also ordered hash sets)
<langsyntaxhighlight lang="nim">import sets
var n = initSet[string]()
n.incl("foo")
 
var o = ["foo", "bar", "baz"].toSet
o.incl("foobar")</langsyntaxhighlight>
 
===Double queues===
<langsyntaxhighlight lang="nim">import deques
var p = initDeque[int]()
p.addLast(12)
p.addFirst(13)
echo p.popFirst()
echo p.popLast()</langsyntaxhighlight>
 
=={{header|Objeck}}==
===vector===
<langsyntaxhighlight lang="objeck">
values := IntVector->New();
values->AddBack(7);
values->AddBack(3);
values->AddBack(10);
</syntaxhighlight>
</lang>
 
===linked list===
<langsyntaxhighlight lang="objeck">
values := IntList->New();
values->AddBack(7);
values->AddBack(3);
values->AddBack(10);
</syntaxhighlight>
</lang>
 
===hash===
<langsyntaxhighlight lang="objeck">
values := StringHash->New();
values->Insert("seven", IntHolder->New(7));
values->Insert("three", IntHolder->New(3));
values->Insert("ten", IntHolder->New(10));
</syntaxhighlight>
</lang>
 
===stack===
<langsyntaxhighlight lang="objeck">
values := IntStack->New();
values->Push(7);
values->Push(3);
values->Push(10);
</syntaxhighlight>
</lang>
 
=={{header|Objective-C}}==
Line 2,411 ⟶ 2,657:
Arrays (indexed by an integer), which are also collections, are not shown here.
 
<langsyntaxhighlight lang="objc">#import <Foundation/Foundation.h>
 
void show_collection(id coll)
Line 2,460 ⟶ 2,706:
}
return EXIT_SUCCESS;
}</langsyntaxhighlight>
 
{{out}} (stripped the left-sided log info):
Line 2,478 ⟶ 2,724:
 
Lists are written like so:
<langsyntaxhighlight lang="ocaml">[1; 2; 3; 4; 5]</langsyntaxhighlight>
 
To prepend a single element to a list, use the '''::''' operator:
<langsyntaxhighlight lang="ocaml">1 :: [2; 3; 4; 5]</langsyntaxhighlight>
 
To concatenate two lists, use '''@''':
<langsyntaxhighlight lang="ocaml">[1; 2] @ [3; 4; 5]</langsyntaxhighlight>
 
To concatenate a whole list of lists, use [http://caml.inria.fr/pub/docs/manual-ocaml/libref/List.html#VALflatten List.flatten]:
 
<langsyntaxhighlight lang="ocaml"># List.flatten [[1; 2]; [3; 4]; [5; 6; 7]] ;;
- : int list = [1; 2; 3; 4; 5; 6; 7]</langsyntaxhighlight>
 
Being a ''functional'' programming language, the list is one of the most important collection type. And being an ''impure'' functional programming language there are also imperative collection type, as for example, arrays:
<langsyntaxhighlight lang="ocaml">[| 1; 2; 3; 4; 5 |]</langsyntaxhighlight>
 
The [http://code.google.com/p/ocaml-extlib/ extlib] also provides a type [http://ocaml-extlib.googlecode.com/svn/doc/apiref/Enum.html Enum.t].
Line 2,515 ⟶ 2,761:
A List (or a Pair) can be created using the following syntax :
 
<langsyntaxhighlight Oforthlang="oforth">[ 1, 1.2, "abcd", [ 1, 2, 3 ] ]</langsyntaxhighlight>
 
In order to add values to a collection, you have to use a ListBuffer (a mutable collection) :
 
<langsyntaxhighlight Oforthlang="oforth">ListBuffer new dup add(10) dup add("aaa") dup add(Date now) dup add(1.3) println </langsyntaxhighlight>
 
{{out}}
Line 2,531 ⟶ 2,777:
ooRexx arrays are sequential lists of object references. The index values are the numeric position (1-based) within the array.
A given array may be sparse and arrays will be automatically expanded as needed.
<syntaxhighlight lang="oorexx">
<lang ooRexx>
a = .array~new(4) -- creates an array of 4 items, with all slots empty
say a~size a~items -- size is 4, but there are 0 items
Line 2,537 ⟶ 2,783:
a[5] = "Mike" -- assigns a value to the fifth slot, expanding the size
say a~size a~items -- size is now 5, with 2 items
</syntaxhighlight>
</lang>
 
;Lists
Line 2,543 ⟶ 2,789:
and the positions will be adjusted accordingly. Lists are indexed using index cookies that are assigned when
an entry is added to the list and can be used to access entries or traverse through the list.
<syntaxhighlight lang="oorexx">
<lang ooRexx>
l = .list~new -- lists have no inherent size
index = l~insert('123') -- adds an item to this list, returning the index
Line 2,553 ⟶ 2,799:
say item
end
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,565 ⟶ 2,811:
Queues are non-sparse sequential lists of object references. The index values are by numeric position (1-based), although access to
items is traditionally done by pushing or popping objects.
<syntaxhighlight lang="oorexx">
<lang ooRexx>
q = .queue~of(2,4,6) -- creates a queue containing 3 items
say q[1] q[3] -- displays "2 6"
Line 2,573 ⟶ 2,819:
q[1] = q[1] + 1 -- updates the first item
say q[1] q[3] -- displays "5 2"
</syntaxhighlight>
</lang>
 
;Tables
Tables are collections that create a one-to-one relationship between an index object and a referenced object.
Although frequently used with string indexes, the index object can be of any class, with index identity determined by the "==" method.
<syntaxhighlight lang="oorexx">
<lang ooRexx>
t = .table~new
t['abc'] = 1
t['def'] = 2
say t['abc'] t['def'] -- displays "1 2"
</syntaxhighlight>
</lang>
 
;Relations
Relation collections create one-to-many data relationships. An addition to the collection will always create a new entry.
<syntaxhighlight lang="oorexx">
<lang ooRexx>
t = .table~new -- a table example to demonstrate the difference
t['abc'] = 1 -- sets an item at index 'abc'
Line 2,600 ⟶ 2,846:
say item
end
</syntaxhighlight>
</lang>
 
;Directories
Directory objects are like tables, but the index values must always be string objects.
<syntaxhighlight lang="oorexx">
<lang ooRexx>
d = .directory~new
d['abc'] = 1
d['def'] = 2
say d['abc'] d['def'] -- displays "1 2"
</syntaxhighlight>
</lang>
Directory objects also support an UNKNOWN method that map messages to directory index entries. This allows
values to be set as if they were object attributes. The following example is another way of doing the same as
the first example:
<syntaxhighlight lang="oorexx">
<lang ooRexx>
d = .directory~new
d~abc = 1
d~def = 2
say d~abc d~def -- displays "1 2"
</syntaxhighlight>
</lang>
Note that the index entries created in the example are the uppercase 'ABC' and 'DEF'.
 
Line 2,624 ⟶ 2,870:
Sets are unordered collections where the items added to the collection are unique values. Duplicate additions are collapsed to just a
single item. Sets are useful for collecting unique occurrences of items.
<syntaxhighlight lang="oorexx">
<lang ooRexx>
s = .set~new
text = "the quick brown fox jumped over the lazy dog"
Line 2,632 ⟶ 2,878:
 
say "text has" text~words", but only" s~items "unique words"
</syntaxhighlight>
</lang>
 
=={{header|Oz}}==
The most important collection types are lists, records, dictionaries and arrays:
<langsyntaxhighlight lang="oz">declare
%% Lists (immutable, recursive)
Xs = [1 2 3 4]
Line 2,660 ⟶ 2,906:
Arr = {Array.new 1 10 initValue}
Arr.1 := 3
{Show Arr.1} %% output: 3</langsyntaxhighlight>
 
There are also [http://www.mozart-oz.org/home/doc/base/tuple.html tuples] (records with consecutive integer keys starting with 1), [http://www.mozart-oz.org/documentation/base/weakdictionary.html weak dictionaries], [http://www.mozart-oz.org/documentation/mozart-stdlib/adt/queue.html queues] and [http://www.mozart-oz.org/documentation/mozart-stdlib/adt/stack.html stacks].
Line 2,666 ⟶ 2,912:
=={{header|PARI/GP}}==
Pari has vectors, column vectors, matrices, sets, lists, small vectors, and maps.
<langsyntaxhighlight lang="parigp">v = vector(0);
v = [];
cv = vectorv(0);
Line 2,674 ⟶ 2,920:
l = List(v);
vs = vectorsmall(0);
M = Map()</langsyntaxhighlight>
Adding members:
<langsyntaxhighlight lang="parigp">listput(l, "hello world")
v=concat(v, [1,2,3]);
v=concat(v, 4);
mapput(M, "key", "value");</langsyntaxhighlight>
 
=={{header|Pascal}}==
Different implementations of Pascal have various containers.
===Array ===
<syntaxhighlight lang="pascal">var
<lang Pascal>var
MyArray: array[1..5] of real;
begin
MyArray[1] := 4.35;
end;</langsyntaxhighlight>
===Dynamic Array ===
<syntaxhighlight lang="pascal">var
<lang Pascal>var
MyArray: array of integer;
begin
setlength (MyArray, 10);
MyArray[4] := 99;
end;</langsyntaxhighlight>
===Record ===
<syntaxhighlight lang="pascal">var
<lang Pascal>var
MyRecord: record
x, y, z: real;
Line 2,707 ⟶ 2,953:
MyRecord.z := -4.0;
MyRecord.presence := true;
end;</langsyntaxhighlight>
 
===Set ===
<syntaxhighlight lang="pascal">type
<lang Pascal>type
days = (Mon, Tue, Wed, Thu, Fri, Sat, Sun);
var
Line 2,718 ⟶ 2,964:
week := workdays + [Sat, Sun];
weekendDays := week - workdays;
end;</langsyntaxhighlight>
 
===String ===
<syntaxhighlight lang="pascal">var
<lang Pascal>var
MyString: String;
begin
MyString:= 'Some Text';
end;</langsyntaxhighlight>
===List ===
{{works with|Free_Pascal}}
{{libheader|Classes}}
<langsyntaxhighlight Pascallang="pascal">program ListDemo;
uses
classes;
Line 2,747 ⟶ 2,993:
writeln (integer(MyList.Items[i]^));
MyList.Destroy;
end.</langsyntaxhighlight>
 
{{out}}
Line 2,759 ⟶ 3,005:
{{works with|Free_Pascal}}
{{libheader|Objects}}
<langsyntaxhighlight Pascallang="pascal">Program ex34;
 
{ Program to demonstrate the TCollection.AtInsert method }
Line 2,792 ⟶ 3,038:
C^.Foreach(@PrintField);
Dispose(C, Done);
end.</langsyntaxhighlight>
 
=={{header|Perl}}==
Perl has ''array'' and ''hashes''.
 
<langsyntaxhighlight lang="perl">use strict;
my @c = (); # create an empty "array" collection
 
Line 2,814 ⟶ 3,060:
foreach my $i ( keys %h ) {
print $i . " -> " . $h{$i} . "\n";
}</langsyntaxhighlight>
 
=={{header|Phix}}==
Collections can simply be stored as sequences
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">collection</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{}</span>
Line 2,824 ⟶ 3,070:
<span style="color: #000000;">collection</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">prepend</span><span style="color: #0000FF;">(</span><span style="color: #000000;">collection</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">?</span> <span style="color: #000000;">collection</span> <span style="color: #000080;font-style:italic;">-- {2,"one"}</span>
<!--</langsyntaxhighlight>-->
If you want uniqueness, you could simply use a dictionary with values of 0:
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #7060A8;">setd</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"one"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0</span><span style="color: #0000FF;">)</span>
Line 2,835 ⟶ 3,081:
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #7060A8;">traverse_dict</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">routine_id</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"visitor"</span><span style="color: #0000FF;">))</span> <span style="color: #000080;font-style:italic;">-- shows 2, "one"</span>
<!--</langsyntaxhighlight>-->
 
=={{header|PHP}}==
PHP has ''associative arrays'' as collection
 
<langsyntaxhighlight lang="php"><?php
$a = array();
# add elements "at the end"
Line 2,849 ⟶ 3,095:
$a['two'] = 2;
print_r($a);
?></langsyntaxhighlight>
 
{{out}}
Line 2,866 ⟶ 3,112:
[two] => 2
)</pre>
 
=={{header|Picat}}==
===Lists===
<syntaxhighlight lang="picat">go =>
L = [1,2,3,4],
L2 = L ++ [[5,6,7]], % adding a list
L3 = ["a string"] ++ L2, % adding a string
 
% Prolog way
append([0],L,[5],L4).</syntaxhighlight>
 
===Arrays===
Array are often used instead of lists for speed. The array literal use <code>{...}</code> (instead of the lists <code>[...]</code>).
<syntaxhighlight lang="picat">go2 =>
L = {1,2,3,4},
L2 = {0} ++ L ++ {5},
 
% multi dimensional arrays
M = new_array(4,4),
bind_vars(M,0). % initialize to 0</syntaxhighlight>
 
===Maps===
Associative arrays/Dictionaries.
<syntaxhighlight lang="picat">go3 =>
Map = new_map(),
Map.put(a,1),
Map.put(b,2),
 
% Initialize map with values
Map2 = new_map([c=3,d="some value"]).</syntaxhighlight>
 
===Sets===
A set is a map where every key is associated with the atom 'not_a_value'. All of the built-ins for maps can be applied to sets.
<syntaxhighlight lang="picat">go4 =>
S = new_set([1,2,3,4,5,"picat"]),
S.put(1),
S.put(21).</syntaxhighlight>
 
===Structures===
A structure takes the form <code>$s(t1,...,tn)</code>, where <code>s</code> is an atom, and n is called the arity of the
structure. The dollar symbol is used to distinguish a structure from a function call.
<syntaxhighlight lang="picat">go5 =>
S = new_struct(a_struct,5),
S[2] = 4, % place 4 at position 2
arg(3,S,"string"). % place "string" at position 3</syntaxhighlight>
 
===Heaps===
A heap is a complete binary tree represented as an array. A heap can be a min-heap or a max-heap. In a min-heap, the value at the root of each subtree is the minimum among all the values in the subtree. In a max-heap, the value at the root of each subtree is the maximum among all the values in the subtree.
<syntaxhighlight lang="picat">go6 =>
L = [1,3,2,4,5,3,6],
H = new_min_heap(L),
H.heap_push(-123).</syntaxhighlight>
 
 
=={{header|PicoLisp}}==
Line 2,871 ⟶ 3,170:
[http://software-lab.de/doc/refI.html#idx index] trees or
[http://software-lab.de/doc/ref.html#symbol property] lists).
<langsyntaxhighlight PicoLisplang="picolisp">: (setq Lst (3 4 5 6))
-> (3 4 5 6)
 
Line 2,884 ⟶ 3,183:
 
: (insert 4 Lst 'X)
-> (1 2 3 X 4 5 6)</langsyntaxhighlight>
 
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
<lang PL/I>
declare countries character (20) varying controlled;
allocate countries initial ('Britain');
allocate countries initial ('America');
allocate countries initial ('Argentina');
</syntaxhighlight>
</lang>
 
=={{header|PowerShell}}==
Line 2,898 ⟶ 3,197:
===Array===
The array index is zero based.
<syntaxhighlight lang="powershell">
<lang PowerShell>
# Create an Array by separating the elements with commas:
$array = "one", 2, "three", 4
Line 2,946 ⟶ 3,245:
 
$multiArray[2,2] # returns 33
</syntaxhighlight>
</lang>
===Hash Table===
Hash tables come in two varieties: normal and ordered, where of course, the order of entry is retained.
<syntaxhighlight lang="powershell">
<lang PowerShell>
# An empty Hash Table:
$hash = @{}
Line 2,996 ⟶ 3,295:
Vikings = "Minnesota"
}
</syntaxhighlight>
</lang>
===Other Collection Types===
PowerShell is a .NET language so '''all''' of the collection types in .NET are available to PowerShell. The most commonly used would probably be <code>[System.Collections.ArrayList]</code>.
<syntaxhighlight lang="powershell">
<lang PowerShell>
$list = New-Object -TypeName System.Collections.ArrayList -ArgumentList 1,2,3
 
Line 3,009 ⟶ 3,308:
$list.Add(4) | Out-Null
$list.RemoveAt(2)
</syntaxhighlight>
</lang>
 
=={{header|Prolog}}==
Traditionally Prolog supports only lists.
<langsyntaxhighlight lang="prolog">% create a list
L = [a,b,c,d],
Line 3,023 ⟶ 3,322:
 
% delete from list
exclude(=(b), L3, L4).</langsyntaxhighlight>
Output:
<pre>
Line 3,034 ⟶ 3,333:
SWI-Prolog supports some other collection types as built in libraries, the most notable is the Dict.
Dicts can be accessed using a special notation and can be added and removed from in an immutable way.
<langsyntaxhighlight lang="prolog">% create an empty dict call 'point'
D1 = point{},
 
Line 3,047 ⟶ 3,346:
 
% access a value randomly
format('x = ~w, y = ~w~n', [D4.x, D4.y]).</langsyntaxhighlight>
Output:
<pre>
Line 3,060 ⟶ 3,359:
===Arrays===
Creating an [http://www.purebasic.com/documentation/array/index.html Array] of 10 strings (could be any type). PureBasic starts the index with element 0.
<langsyntaxhighlight PureBasiclang="purebasic">Dim Text.s(9)
 
Text(3)="Hello"
Text(7)="World!"</langsyntaxhighlight>
 
===Linked Lists===
Create a [http://www.purebasic.com/documentation/linkedlist/index.html Linked List] for strings (could be any type), then add two elements.
<langsyntaxhighlight PureBasiclang="purebasic">NewList Cars.s()
 
AddElement(Cars()): Cars()="Volvo"
AddElement(Cars()): Cars()="BMV"</langsyntaxhighlight>
 
===Hash table===
Create a [http://www.purebasic.com/documentation/map/index.html Map], e.g. a hash table that could be any type. The size of the dictionary can be defined as needed, otherwise a default value is used.
<langsyntaxhighlight PureBasiclang="purebasic">NewMap Capitals.s()
 
Capitals("USA") = "Washington"
Capitals("Sweden")= "Stockholm"</langsyntaxhighlight>
 
=={{header|Python}}==
{{works with|Python|2.5}}
Python supports lists, tuples, dictionaries and now sets as built-in collection types. See http://docs.python.org/tut/node7.html for further details.
<langsyntaxhighlight lang="python">collection = [0, '1'] # Lists are mutable (editable) and can be sorted in place
x = collection[0] # accessing an item (which happens to be a numeric 0 (zero)
collection.append(2) # adding something to the end of the list
Line 3,101 ⟶ 3,400:
collection = {0: "zero", 1: "one"} # Dictionaries (Hash)
collection['zero'] = 2 # Dictionary members accessed using same syntax as list/array indexes.
collection = set([0, '1']) # sets (Hash)</langsyntaxhighlight>
 
In addition Python classes support a number of methods allowing them to implement indexing, slicing, and attribute management features as collections. Thus many modules in the Python standard libraries allow one to treat files contents, databases, and other data using the same syntax as the native collection types. Some Python modules (such as Numeric and NumPy) provide low-level implementations of additional collections (such as efficient n-dimensional arrays).
Line 3,109 ⟶ 3,408:
===Vectors===
Numeric (floating point)
<langsyntaxhighlight Rlang="r">numeric(5)
1:10
c(1, 3, 6, 10, 7 + 8, sqrt(441))</langsyntaxhighlight>
[1] 0 0 0 0 0
[1] 1 2 3 4 5 6 7 8 9 10
[1] 1 3 6 10 15 21
Integer
<langsyntaxhighlight Rlang="r">integer(5)
c(1L, -2L, 99L);</langsyntaxhighlight>
[1] 0 0 0 0 0
[1] 1 -2 99
Logical
<langsyntaxhighlight Rlang="r">logical(5)
c(TRUE, FALSE)</langsyntaxhighlight>
[1] FALSE FALSE FALSE FALSE FALSE
[1] TRUE FALSE
Character
<langsyntaxhighlight Rlang="r">character(5)
c("abc", "defg", "")</langsyntaxhighlight>
[1] "" "" "" "" ""
[1] "abc" "defg" ""
===Arrays and Matrices===
These are essentially vectors with a dimension attribute. Matrices are just arrays with two dimensions (and a different class).
<langsyntaxhighlight Rlang="r">matrix(1:12, nrow=3)
 
array(1:24, dim=c(2,3,4)) #output not shown</langsyntaxhighlight>
[,1] [,2] [,3] [,4]
[1,] 1 4 7 10
Line 3,141 ⟶ 3,440:
===Lists===
Lists are collections of other variables (that can include other lists).
<langsyntaxhighlight Rlang="r">list(a=123, b="abc", TRUE, 1:5, c=list(d=runif(5), e=5+6))</langsyntaxhighlight>
<langsyntaxhighlight lang="r">$a
[1] 123
$b
Line 3,154 ⟶ 3,453:
[1] 0.6013157 0.5011909 0.7106448 0.3882265 0.1274939
$c$e
[1] 11</langsyntaxhighlight>
===Data Frames===
Data frames are like a cross between a list and a matrix. Each row represents one "record", or a collection of variables.
<langsyntaxhighlight Rlang="r">data.frame(name=c("Alice", "Bob", "Carol"), age=c(23, 35, 17))</langsyntaxhighlight>
name age
1 Alice 23
Line 3,166 ⟶ 3,465:
 
As in other lisps, the simple kind of linked lists are the most common collection-of-values type.
<syntaxhighlight lang="racket">
<lang Racket>
#lang racket
 
Line 3,175 ⟶ 3,474:
;; add an element to the front of a list (non-destructively)
(cons 1 (list 2 3 4))
</syntaxhighlight>
</lang>
Racket comes with about 7000 additional types that can be considered as a collection of values, but it's not clear whether this entry is supposed to be a laundry list...
 
Line 3,183 ⟶ 3,482:
Raku has both mutable and immutable containers of various sorts. Here are some of the most common ones:
===Mutable===
<syntaxhighlight lang="raku" perl6line># Array
my @array = 1,2,3;
@array.push: 4,5,6;
Line 3,198 ⟶ 3,497:
# BagHash
my $b = BagHash.new: <b a k l a v a>;
$b ⊎= <a b c>;</langsyntaxhighlight>
 
===Immutable===
<syntaxhighlight lang="raku" perl6line># List
my @list := 1,2,3;
my @newlist := |@list, 4,5,6; # |@list will slip @list into the surrounding list instead of creating a list of lists
Line 3,211 ⟶ 3,510:
# Bag
my $bag = bag <b a k l a v a>;
my $newbag = $bag ⊎ <b e e f>;</langsyntaxhighlight>
 
===Pair list (cons list)===
<syntaxhighlight lang="raku" perl6line>my $tail = d => e => f => Nil;
my $new = a => b => c => $tail;</langsyntaxhighlight>
 
===P6opaque object (immutable in structure)===
<syntaxhighlight lang="raku" perl6line>class Something { has $.foo; has $.bar };
my $obj = Something.new: foo => 1, bar => 2;
my $newobj = $obj but role { has $.baz = 3 } # anonymous mixin</langsyntaxhighlight>
 
=={{header|Raven}}==
Line 3,226 ⟶ 3,525:
Numerically indexed List:
 
<langsyntaxhighlight lang="raven">[ 1 2 3 'abc' ] as a_list
a_list print
 
Line 3,233 ⟶ 3,532:
1 => 2
2 => 3
3 => "abc"</langsyntaxhighlight>
 
String key indexed Hash:
 
<langsyntaxhighlight lang="raven">{ 'a' 1 'b' 2 } as a_hash
a_hash print
 
hash (2 items)
a => 1
b => 2</langsyntaxhighlight>
 
Set items:
 
<langsyntaxhighlight lang="raven">17 a_list 1 set # set second item
42 a_hash 'b' set # set item with key 'b'
42 a_hash:b # shorthand</langsyntaxhighlight>
 
Get items:
 
<langsyntaxhighlight lang="raven">a_list 1 get # get second item
a_hash 'b' get # get item with key 'b'
a_hash.b # shorthand</langsyntaxhighlight>
 
Other stuff:
 
<langsyntaxhighlight lang="raven">42 a_list push # append an item
a_list pop # remove last item
42 a_list shove # prepend an item
a_list shift # remove first item
42 a_list 1 insert # insert item second, shuffling others down
a_list 1 remove # retrieve second item, shuffling others up</langsyntaxhighlight>
 
=={{header|REXX}}==
Line 3,279 ⟶ 3,578:
To store (say) a collection of numbers &nbsp; (or anything,
for that matter) &nbsp; into a stemmed array:
<langsyntaxhighlight lang="rexx">pr. = /*define a default for all elements for the array*/
 
pr.1 = 2 /*note that this array starts at 1 (one). */
Line 3,316 ⟶ 3,615:
do n=-5 to 5 /*define a stemmed array from -5 to 5 */
sawtooth.n = n /*the sawtooth array is, well, a sawtooth curve*/
end /*n*/ /*note that eleven elements will be defined. */</langsyntaxhighlight>
Most often, programmers will assign the &nbsp; zero &nbsp; entry to the
number of elements in the stemmed array.
Line 3,322 ⟶ 3,621:
This means that any index of the stemmed array must be positive to be useful for
storing numbers.
<langsyntaxhighlight lang="rexx"> pr.0= 15 /*number of (data) entries in the stemmed array. */</langsyntaxhighlight>
Programmatically, a simple test could be performed to detect the
end of the array &nbsp; (if there aren't any &nbsp; ''null'' &nbsp; values):
<langsyntaxhighlight lang="rexx"> do j=1 while pr.j\==''
say 'prime' j "is" pr.j
end /*j*/
/*at this point, J=16 (because of the DO */
/*loop incrementing the index. */
j= j-1 /*J now has the count of primes stored. */</langsyntaxhighlight>
 
===lists or vectors===
To store (say) a collection of numbers (or anything, for that matter) into a list:
<langsyntaxhighlight lang="rexx">primeList = '2 3 5 7 11 13 17 19 23 29 31 37 41 43' /* or ··· */
primeList = 2 3 5 7 11 13 17 19 23 29 31 37 41 43
 
Line 3,348 ⟶ 3,647:
/*very efficient for very large arrays (those */
/*with many many thousands of elements). */
end /*j*/</langsyntaxhighlight>
The use of lists (in the above manner) is suitable for words (or numbers) that do not have
leading, embedded, or
Line 3,360 ⟶ 3,659:
To store (for instance) a collection of numbers (or anything, for that matter) into
a sparse stemmed array:
<langsyntaxhighlight lang="rexx">pr. = 0 /*define a default for all elements for the array.*/
pr.2 = 1
pr.3 = 1
Line 3,409 ⟶ 3,708:
end /*k*/
 
say 'The number of primes found in the list is: ' #</langsyntaxhighlight><br><br>
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
text = list(2)
text[1] = "Hello "
text[2] = "world!"
see text[1] + text[2] + nl
</syntaxhighlight>
</lang>
Output:
<pre>
Line 3,427 ⟶ 3,726:
===Array===
Arrays are ordered, integer-indexed collections of any object.
<langsyntaxhighlight lang="ruby"># creating an empty array and adding values
a = [] #=> []
a[0] = 1 #=> [1]
Line 3,437 ⟶ 3,736:
a = Array.new(3) #=> [nil, nil, nil]
a = Array.new(3, 0) #=> [0, 0, 0]
a = Array.new(3){|i| i*2} #=> [0, 2, 4]</langsyntaxhighlight>
 
===Hash===
A Hash is a dictionary-like collection of unique keys and their values. Also called associative arrays, they are similar to Arrays, but where an Array uses integers as its index, a Hash allows you to use any object type.
<langsyntaxhighlight lang="ruby"># creating an empty hash
h = {} #=> {}
h["a"] = 1 #=> {"a"=>1}
Line 3,462 ⟶ 3,761:
#=> {}
p h[1] #=> "foo1"
p h #=> {1=>"foo1"}</langsyntaxhighlight>
 
===Struct===
A Struct is a convenient way to bundle a number of attributes together, using accessor methods, without having to write an explicit class.
<langsyntaxhighlight lang="ruby"># creating a struct
 
Person = Struct.new(:name, :age, :sex)
Line 3,487 ⟶ 3,786:
 
c = Person["Daniel", 22, :Man]
p c.to_h #=> {:name=>"Daniel", :age=>22, :sex=>:Man}</langsyntaxhighlight>
 
===Set===
Set implements a collection of unordered values with no duplicates. This is a hybrid of Array's intuitive inter-operation facilities and Hash's fast lookup.
 
<langsyntaxhighlight lang="ruby">require 'set'
 
# different ways of creating a set
Line 3,512 ⟶ 3,811:
p s1.add(5) #=> #<Set: {1, 2, 3, 4, 5}>
p s1 << 0 #=> #<Set: {1, 2, 3, 4, 5, 0}>
p s1.delete(3) #=> #<Set: {1, 2, 4, 5, 0}></langsyntaxhighlight>
 
===Matrix and Vector===
The Matrix and Vector class represents a mathematical matrix and vector.
<langsyntaxhighlight lang="ruby">require 'matrix'
 
# creating a matrix
Line 3,539 ⟶ 3,838:
 
p m1 * v1 #=> Vector[1, 3, 5]
p m3 * v1 #=> Vector[-13, -4, 5]</langsyntaxhighlight>
 
===OpenStruct===
An OpenStruct is a data structure, similar to a Hash, that allows the definition of arbitrary attributes with their accompanying values.
<langsyntaxhighlight lang="ruby">require 'ostruct'
 
# creating a OpenStruct
Line 3,565 ⟶ 3,864:
son.items = ["candy","toy"]
p son.items #=> ["candy","toy"]
p son #=> #<OpenStruct name="Thomas", age=4, items=["candy", "toy"]</langsyntaxhighlight>
 
=={{header|Rust}}==
Line 3,572 ⟶ 3,871:
====Array====
Arrays (<code>[T]</code>) are stack allocated, fixed size collections of items of the same type.
<langsyntaxhighlight lang="rust">let a = [1u8,2,3,4,5]; // a is of type [u8; 5];
let b = [0;256] // Equivalent to `let b = [0,0,0,0,0,0... repeat 256 times]`</langsyntaxhighlight>
====Slice====
Slices (<code>&[T]</code>) are dynamically sized views into contiguous sequences (arrays, vectors, strings)
<langsyntaxhighlight lang="rust">let array = [1,2,3,4,5];
let slice = &array[0..2]
println!("{:?}", slice);</langsyntaxhighlight>
{{out}}
<pre>[1,2]</pre>
Line 3,594 ⟶ 3,893:
* You want a heap-allocated array.
 
<langsyntaxhighlight lang="rust">let mut v = Vec::new();
v.push(1);
v.push(2);
v.push(3);
// Or (mostly) equivalently via a convenient macro in the standard library
let v = vec![1,2,3];</langsyntaxhighlight>
====String====
<code>String</code>s are growable strings stored as a UTF-8 buffer which are just <code>Vec<u8></code>s under the hood. Like <code>str</code>s, they are not indexable (for the same reasons) but iterators can be created over the graphemes, codepoints or bytes therein.
<langsyntaxhighlight lang="rust">let x = "abc"; // x is of type &str (a borrowed string slice)
let s = String::from(x);
// or alternatively
let s = x.to_owned();</langsyntaxhighlight>
 
====VecDequeue====
Line 3,643 ⟶ 3,942:
The collections are available in two flavors; immutable (these have no methods to modify or update) and mutable. With these properties they are also available in concurrent version for parallel processing. Switching between sequential and parallel can easily be done by adding a .seq or .par post-fix.
 
These examples were taken from a Scala REPL session. The second lines are the REPL responces.<langsyntaxhighlight Scalalang="scala">Windows PowerShell
Copyright (C) 2012 Microsoft Corporation. All rights reserved.
 
Line 3,700 ⟶ 3,999:
res19: queue.type = Queue("first", "second")
 
scala></langsyntaxhighlight>
<langsyntaxhighlight Scalalang="scala"> import collection.concurrent.TrieMap
 
// super concurrent mutable hashmap
Line 3,730 ⟶ 4,029:
map.filter { k => k._1 > 3 } // Map(5 -> 6, 44 -> 99)
// // same with for syntax
for ((k, v) <- map; if k > 3) yield (k, v)</langsyntaxhighlight>
 
=={{header|Scheme}}==
===list===
<syntaxhighlight lang ="scheme">(list obj ...)</langsyntaxhighlight>
returns a newly allocated list of its arguments.
 
Example:
<langsyntaxhighlight lang="scheme">(display (list 1 2 3))
(newline)
(display (list))
(newline)</langsyntaxhighlight>
{{out}}
<pre>(1 2 3)
Line 3,747 ⟶ 4,046:
 
===cons===
<syntaxhighlight lang ="scheme">(cons obj lst)</langsyntaxhighlight>
returns a newly allocated list consisting of <code>obj</code> prepended to <code>lst</code>.
 
Example:
<langsyntaxhighlight lang="scheme">(display (cons 0 (list 1 2 3)))
(newline)</langsyntaxhighlight>
{{out}}
<pre>(0 1 2 3)</pre>
===append===
<syntaxhighlight lang ="scheme">(append lst ...)</langsyntaxhighlight>
returns a newly allocated list consisting of the elements of <code>lst</code> followed by the elements of the other lists.
 
Example:
<langsyntaxhighlight lang="scheme">(display (append (list 1 2 3) (list 4 5 6)))
(newline)</langsyntaxhighlight>
{{out}}
<pre>(1 2 3 4 5 6)</pre>
Line 3,768 ⟶ 4,067:
 
===set===
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
enable_output(set of string);
Line 3,779 ⟶ 4,078:
incl(aSet, "silver");
writeln(aSet);
end func;</langsyntaxhighlight>
 
===array===
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
const proc: main is func
Line 3,798 ⟶ 4,097:
end for;
writeln;
end func;</langsyntaxhighlight>
 
===hash===
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
const type: aHashType is hash [string] string;
Line 3,816 ⟶ 4,115:
writeln(aKey <& ": " <& aValue);
end for;a
end func;</langsyntaxhighlight>
 
=={{header|Setl4}}==
 
===Set===
<langsyntaxhighlight lang="setl4">
set = new('set 5 10 15 20 25 25')
add(set,30)
Line 3,831 ⟶ 4,130:
show.eval("exists(set,'eq(this,10)')")
show.eval("forall(set,'eq(this,40)')")
</syntaxhighlight>
</lang>
===Iter===
<langsyntaxhighlight lang="setl4">
iter = new('iter 1 10 2')
show(iter)
show.eval("eq(set.size(iter),5)")
show.eval('member(iter,5)')
</syntaxhighlight>
</lang>
===Map===
<langsyntaxhighlight lang="setl4">
map = new('map one:1 two:2 ten:10 forty:40 hundred:100 thousand:1000')
show(map)
Line 3,848 ⟶ 4,147:
show.eval("exists(map,'eq(get(map,this),2)')")
show.eval("forall(map,'eq(get(map,this),2)')")
</syntaxhighlight>
</lang>
 
=={{header|Sidef}}==
===Array===
Arrays are ordered, integer-indexed collections of any object.
<langsyntaxhighlight lang="ruby"># creating an empty array and adding values
var a = [] #=> []
a[0] = 1 #=> [1]
a[3] = "abc" #=> [1, nil, nil, "abc"]
a << 3.14 #=> [1, nil, nil, "abc", 3.14]</langsyntaxhighlight>
 
===Hash===
A Hash is a dictionary-like collection of unique keys and their values. Also called associative arrays, they are similar to Arrays, but where an Array uses integers as its index, a Hash allows you to use any object type, which is automatically converted into a String.
<langsyntaxhighlight lang="ruby"># creating an empty hash
var h = Hash() #=> Hash()
h{:foo} = 1 #=> Hash("foo"=>1)
h{:bar} = 2.4 #=> Hash("foo"=>1, "bar"=>2.4)
h{:bar} += 3 #=> Hash("foo"=>1, "bar"=>5.4)</langsyntaxhighlight>
 
===Pair===
A Pair is an array-like collection, but restricted only to two elements.
<langsyntaxhighlight lang="ruby"># create a simple pair
var p = Pair('a', 'b')
say p.first; #=> 'a'
Line 3,882 ⟶ 4,181:
pair = pair.second;
pair == nil && break;
}</langsyntaxhighlight>
 
===Struct===
A Struct is a convenient way to bundle a number of attributes together.
<langsyntaxhighlight lang="ruby"># creating a struct
struct Person {
String name,
Line 3,900 ⟶ 4,199:
say a.name #=> "Dr. John Smith"
say a.age #=> 42
say a.sex #=> "man"</langsyntaxhighlight>
 
=={{header|Slate}}==
<langsyntaxhighlight lang="slate">{1. 2. 3. 4. 5} collect: [|:x| x + 1]. "--> {2. 3. 4. 5. 6}"
{1. 2. 3. 4. 5} select: #isOdd `er. "--> {1. 3. 5}"
({3. 2. 7} collect: #+ `er <- 3) sort. "--> {"SortedArray traitsWindow" 5. 6. 10}"
ExtensibleArray new `>> [addLast: 3. addFirst: 4. ]. "--> {"ExtensibleArray traitsWindow" 4. 3}"</langsyntaxhighlight>
 
=={{header|Smalltalk}}==
Line 3,919 ⟶ 4,218:
* '''Dictionary''': objects are ''indexed'' by an arbitrary key, e.g. a string
 
<langsyntaxhighlight lang="smalltalk">|anOrdered aBag aSet aSorted aSorted2 aDictionary|
 
anOrdered := OrderedCollection new.
Line 3,950 ⟶ 4,249:
at: 'Set' put: aSet;
at: 'SortedCollection' put: { aSorted. aSorted2 }.
aDictionary printNl.</langsyntaxhighlight>
 
Output:
Line 3,969 ⟶ 4,268:
 
A Tcl list is called an array in other languages (an integer-indexed list of values).
<langsyntaxhighlight lang="tcl">set c [list] ;# create an empty list
# fill it
lappend c 10 11 13
Line 3,980 ⟶ 4,279:
puts [llength $l]
}
show_size $c</langsyntaxhighlight>
 
A Tcl array is an associative array (aka hash). Arrays are collections of ''variables'' indexable by name, and not collections of values. An array cannot be passed to a procedure be value: it must either be passed by name or by its serialized representation. Tcl arrays also are strictly one-dimensional: arrays cannot be nested. However, multi-dimensional arrays can be simulated with cleverly constructed key strings.
 
<langsyntaxhighlight lang="tcl"># create an empty array
array set h {}
# add some pair
Line 4,007 ⟶ 4,306:
puts "array has [llength [array names arr]] keys"
}
numkeys_bycopy [array get h]</langsyntaxhighlight>
 
{{works with|Tcl|8.5}}
Line 4,013 ⟶ 4,312:
A Tcl dictionary is an associative array ''value'' that contains other values. Hence dictionaries can be nested and arbitrarily deep data structures can be created.
 
<langsyntaxhighlight lang="tcl"># create an empty dictionary
set d [dict create]
dict set d one 1
Line 4,021 ⟶ 4,320:
set f [dict merge $d $e]
dict set f nested [dict create five 5 more [list 6 7 8]]
puts [dict get $f nested more] ;# ==> 6 7 8</langsyntaxhighlight>
 
=={{header|TUSCRIPT}}==
<langsyntaxhighlight lang="tuscript">
$$ MODE TUSCRIPT
 
Line 4,038 ⟶ 4,337:
collection=APPEND(collection,morestuff)
TRACE *collection
</syntaxhighlight>
</lang>
Output:
<pre>
Line 4,054 ⟶ 4,353:
{{works with|bash}}
{{works with|ksh}}
<langsyntaxhighlight lang="bash">a_index=(one two three) # create an array with a few elements
a_index+=(four five) # append some elements
a_index[9]=ten # add a specific index
Line 4,062 ⟶ 4,361:
for idx in "${!a_index[@]}"; do # interate over the array indices
printf "%d\t%s\n" $idx "${a_index[idx]}"
done</langsyntaxhighlight>
===Associative arrays===
{{works with|bash}}
<langsyntaxhighlight lang="bash">declare -A a_assoc=([one]=1 [two]=2 [three]=3) # create an array with a few elements
a_assoc+=([four]=4 [five]=5) # add some elements
a_assoc[ten]=10
Line 4,073 ⟶ 4,372:
for key in "${!a_assoc[@]}"; do # interate over the array indices
printf "%s\t%s\n" "$key" "${a_assoc[$key]}"
done</langsyntaxhighlight>
{{works with|ksh}}
Change <langsyntaxhighlight lang="bash">declare -A</langsyntaxhighlight> to <syntaxhighlight lang ="bash">typeset -A</langsyntaxhighlight>
 
=={{header|Ursala}}==
Line 4,091 ⟶ 4,390:
Lists are written as comma-separated sequences enclosed in
angle brackets, or with the head and tail separated by a colon.
<langsyntaxhighlight Ursalalang="ursala">x = <1,5,6>
y = <'foo','bar'>
z = 3:<6,8></langsyntaxhighlight>
This function takes a pair of a new head and an existing list,
and returns one that has the new head "added" to it.
<langsyntaxhighlight Ursalalang="ursala">foo ("newhead","existing-list") = "newhead":"existing-list"</langsyntaxhighlight>
===Sets===
 
Line 4,102 ⟶ 4,401:
The order and multiplicities of elements are ignored, so that the followng
declarations are equivalent.
<langsyntaxhighlight Ursalalang="ursala">x = {'a','b'}
y = {'b','a'}
z = {'a','b','a'}</langsyntaxhighlight>
 
===Modules===
Line 4,110 ⟶ 4,409:
Modules are lists in a particular form used to represent
key:value pairs, with the key being a character string.
<langsyntaxhighlight Ursalalang="ursala">m = <'foo': 1,'bar': 2,'baz': 3></langsyntaxhighlight>
A module or any list of pairs can be reified into a function
(a.k.a., a hash or finite map) and used in any context where a function is usable,
Line 4,119 ⟶ 4,418:
where <math>r</math> is the root and <math>s</math> is a list of subtrees, which can
be of any length.
<syntaxhighlight lang="ursala">x =
<lang Ursala>x =
 
'z'^: <
Line 4,127 ⟶ 4,426:
'a'^: <'E'^: <>,'j'^: <>>,
'b'^: <'i'^: <>>,
'c'^: <>></langsyntaxhighlight>
 
===A-trees===
Line 4,134 ⟶ 4,433:
representation wherein data are stored only in the leaves at a
constant depth.
<syntaxhighlight lang="ursala">x =
<lang Ursala>x =
 
[
Line 4,141 ⟶ 4,440:
4:2: 'baz',
4:3: 'volta',
4:4: 'pramim']</langsyntaxhighlight>
===Grids===
 
Line 4,154 ⟶ 4,453:
of its descendents in the next level.
 
<syntaxhighlight lang="ursala">g =
<lang Ursala>g =
 
<
Line 4,176 ⟶ 4,475:
4:12: -3.460494e+00^: <>,
4:9: 2.840319e+00^: <>,
4:7: -2.181140e+00^: <>]></langsyntaxhighlight>
 
=={{header|V}}==
A quote is used for the same purpose in V
<langsyntaxhighlight lang="v">[4 3 2 1] 5 swap cons
=[5 4 3 2 1]</langsyntaxhighlight>
 
=={{header|VBA}}==
VBA has a built in collection type
<langsyntaxhighlight lang="vb">Dim coll As New Collection
coll.Add "apple"
coll.Add "banana"</langsyntaxhighlight>
 
=={{header|Vim Script}}==
Line 4,196 ⟶ 4,495:
=={{header|Visual Basic .NET}}==
 
<langsyntaxhighlight lang="vbnet">Dim toys As New List(Of String)
toys.Add("Car")
toys.Add("Boat")
toys.Add("Train")</langsyntaxhighlight>
 
=={{header|Visual FoxPro}}==
Visual FoxPro has a built in Collection class.
 
<langsyntaxhighlight lang="vfp">
LOCAL loColl As Collection, o, a1, a2, a3
a1 = CREATEOBJECT("animal", "dog", 4)
Line 4,227 ⟶ 4,526:
 
ENDDEFINE
</syntaxhighlight>
</lang>
 
=={{header|Wren}}==
Wren has only Map(hash) and List(array).
<langsyntaxhighlight ecmascriptlang="wren">var list = [] // Empty Array
list = [1, 2, 3, 4]
list.add(5)
Line 4,246 ⟶ 4,545:
for (e in map.keys) {
// Do stuff
}</langsyntaxhighlight>
 
=={{header|Z80 Assembly}}==
Line 4,254 ⟶ 4,553:
A list is just a consecutive section of memory. Lists are mutable if they are in RAM, and are immutable if they are in ROM. Whether they are located in RAM or in ROM depends mostly on the hardware that uses the Z80 CPU. (Typically, programs that are run from CD-ROM or floppy disks can create mutable lists using the method below, but ROM cartridges cannot, even if those cartridges have internal RAM.)
 
<langsyntaxhighlight lang="z80">List:
byte 1,2,3,4,5</langsyntaxhighlight>
 
To append to a list you need to know where it ends, unfortunately the CPU can't know this without some sort of metadata placed at the beginning of a list. In addition, it is important to have enough free space after a list to append to it successfully. Otherwise you'll "clobber" whatever is stored after the list, which could be other data or executable code. (The Z80 has no segfaults or memory protection of any kind; writes to ROM are silently ignored, and executable code in RAM is overwritten like any other mutable data.)
 
<langsyntaxhighlight lang="z80">List:
byte 5 ;size byte
byte 1,2,3,4,5 ;the actual list
Line 4,283 ⟶ 4,582:
pop hl ;go back to beginning of the list.
inc (hl) ;add 1 to the size byte.
ret</langsyntaxhighlight>
 
 
Line 4,289 ⟶ 4,588:
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">Lists: L(1,2,3).append(4); //-->L(1,2,3,4), mutable list
Read only list: ROList(1,2,3).append(4); // creates two lists
 
Line 4,298 ⟶ 4,597:
Data(0,Int,"foo\n","bar").readln() //-->"foo\n"
Data(0,String,"foo ","bar") //-->9 bytes (2 \0s)
Data(0,String,"foo ").append("bar").readln() //-->"foo "</langsyntaxhighlight>
Anonymous user