index<--

# Dart Collections

Dart comes with batteries included. You don't have to create data structures and algorithms. What you chare about is to learn and understand ready made structures that you can customize for your own needs.

#### Built-in Collections

Dart language has special support for the following collections:

## Lists

A list is an enumeration of values. The list literal is an enumeration of literal values or expressions separated by comma and enclosed in square brackets. It looks like a List in python or like an Array in JavaScript:

``````//declare a List object
void main() {
var lst = [1,2,3,];
print(lst);    // [1,2,3]
print(lst[0]); // 1 (first element)
print(lst[1]); // 2 (second element)
print(lst[2]); // 3 (last element)

// check length property
assert(list.length == 3);

// check each element
assert(lst[0] == 1); // check
assert(lst[1] == 2); // check
assert(lst[2] == 3); // check
}
``````

#### Notes:

• Elements of list above will be all integers;
• Element index start from 0 to length-1;
• List index can not be negative;
• Last coma is optional, but is good to know compiler ignores it.

## Sets

This is a special collection that has a wel know theory we learn in school. We know that a "set" is a collection of unique elements. That is, each element is usually a number or a string.

#### Pattern:

There are several ways to define a set. Most common is to use curly brackets {} and separate elements by comma:

``````//an empty set of strings
var persons  = <Strings>{};

//also an empty set of strings
Set<Strings> names = {};

//a set of strings with 3 elements
var fruits = {'apple', 'orange', 'banana'};

//testing some methods
assert(fruits.length == 3);

assert(fruits.length == 4);
``````

## Maps

A map is a special set that store (key:value) pairs. Therefore in some other languages a map is sometimes called dictionary and sometimes hash table. The secret of maps is that "key" is unique, but unlike a set, the key point to some useful data. This property makes maps more useful than sets.

#### Pattern 1:

As for "sets" also we have several ways to define a map.

``````//an empty map

//new elements

//testing some methods

//testing some methods
``````

#### Notes:

• In this example, "marian" and "dani" both get a "bike". That is, the value is not unique, only the key must be unique.
• Though is not a vector or a list, you can put strings in brackets [''] to assign new elements into the map.

#### Pattern 2:

Second way to define a set is by using curly bracket literals {...}.

``````//an empty map
'doru'   : "pony",
'marian' : "bike"
'dani'   : "scutter"
};
``````

#### Pattern 3:

Since Map is a generic class, we can use the more explicit notation that should rarely be used. Dart does a good job using type inference so we don't have to use this notation that is actually the only one available in Java for example.

``````//legacy map declarations