Dart-集合
主要包含
- List
- Set
- Map
List
在 Dart 中的 Array
就是 List
对象, 通常称之为 List
List names = ["Jack", "John"];
print(names[1]);//John
print(names.length);//2
for(var n in names) {
print(n);
}
List中也可以包含不同类型的元素
List names = ["Jack", "John", 100, 100.0];
类型显示如下:
也可以指定元素的类型,如下,会提示出错
可以对List中的元素进行修改
List<String> names = ["Jack", "John"];
names[1] = "Jelly";
如果想定义其中的每个value都是常量,在运行的时候不可改变,可在前面添加一个const
List<String> names = const ["Jack", "John"];
names[1] = "Jelly";
此时运行上面的程序,会提示如下的错误:
Const 关键字不仅可以用于声明常量变量。 还可以用来创建常量值,以及声明创建常量值的构造函数。 任何变量都可以拥有常量值。
在 List 字面量之前添加 const 关键字,可以定义 List 类型的编译时常量:var constantList = const [1, 2, 3]; // constantList[1] = 1; // 取消注释会引起错误。
有时候需要把一个List复制给另一个List,如下的例子,并不是完全复制,修改原List,会影响另一个List
void main() {
List<String> names = ["Jack", "John"];
var names2 = names;
names[1] = "Jelly";
for (var n in names2) {
print(n); //Jack Jelly
}
}
如果想完全复制一个List,可以这样做
Dart 2.3 introduced the spread operator (
...
) and the null-aware spread operator (...?
), which provide a concise way to insert multiple elements into a collection.
提供将多个元素插入到集合中的简洁方法
void main() {
List<String> names = ["Jack", "John"];
var names2 = [...names];
names[1] = "Jelly";
for (var n in names2) {
print(n); //Jack John
}
}
在官方例子Lists中,如下,将一个list的所有元素插入到一个list中
var list = [1, 2, 3];
var list2 = [0, ...list];
print(list2); //[0, 1, 2, 3]
assert(list2.length == 4);
如果list为null,可以使用...?
var list;
var list2 = [0, ...?list];
assert(list2.length == 1);
Dart 2.3 also introduced collection if and collection for, which you can use to build collections using conditionals (if
) and repetition (for
).
collection if
如下的例子,可以创建一个包含三个或者四个元素的list
var nav = [
'Home',
'Furniture',
'Plants',
if (true) 'Outlet'
];
print(nav);//[Home, Furniture, Plants, Outlet]
var nav = [
'Home',
'Furniture',
'Plants',
if (false) 'Outlet'
];
print(nav);//[Home, Furniture, Plants]
collection for
这是一个list添加到另一个list之前,对其进行操作的示例:
var listOfInts = [1, 2, 3];
var listOfStrings = [
'#0',
for (var i in listOfInts) '#$i'
];
print(listOfStrings);//[#0, #1, #2, #3]
assert(listOfStrings[1] == '#1');
Set
如下定义一个set,并且遍历,虽然有3个元素,但其实输出的只有2个元素
var halogens = {'fluorine', 'chlorine', 'fluorine'};
for(var x in halogens) {
print(x);//fluorine chlorine
}
要创建一个空的set,使用类型参数前面使用{}
var names = <String>{};
// Set<String> names = {}; // This works, too.
// var names = {}; // Creates a map, not a set. 不是set,是map
如:
var halogens = {};
print(halogens.runtimeType);//_InternalLinkedHashMap<dynamic, dynamic>
通过输出结果可以发现,上面定义的是一个map
Map
var gifts = {
// Key: Value
'first': 'partridge',
'second': 'turtledoves',
'fifth': 'golden rings'
};
同样可以使用Map
的构造方法
var gifts = Map();
gifts['first'] = 'partridge';
gifts['second'] = 'turtledoves';
gifts['fifth'] = 'golden rings';