Dart编程中的映射
映射是一种非常重要的数据结构,因为它允许我们将键映射到一些特定的值,之后我们可以根据键获取值。
在Dart中,我们有不同类型的映射可用。主要有:
HashMap
LinkedHashMap
SplayTreeMap
在大多数情况下,我们使用LinkedHashMap,因为它非常易于创建和使用。
让我们在Dart中创建一个简单的映射。
示例
考虑以下示例:
void main() {
var colors = new Map();
print(colors);
}在上面的示例中,我们创建了一个空映射并将其打印出来。需要注意的是,当我们使用**Map()**构造函数创建一个映射时,它将创建一个LinkedHashMap。
LinkedHashMap与HashMap的不同之处在于它保留了我们插入键的顺序。
输出
{}现在,让我们尝试向我们的colors映射中添加一些键值对。
示例
考虑以下示例:
void main() {
var colors = new Map();
colors['blue'] = true;
colors['red'] = false;
colors['green'] = false;
colors['yellow'] = true;
print(colors);
}键在方括号内提供,我们要分配给这些键的值位于表达式的右侧。
输出
{blue: true, red: false, green: false, yellow: true}需要注意的是,当我们打印映射时,我们插入键的顺序得以保持。此外,映射中的所有键不必都是相同的数据类型。
示例
考虑以下示例:
void main() {
var colors = new Map();
colors['blue'] = true;
colors['red'] = false;
colors['green'] = false;
colors['yellow'] = true;
colors[1] = "omg"; // int key with string value
print(colors);
}在Dart中,拥有动态键和值是完全可以的。
输出
{blue: true, red: false, green: false, yellow: true, 1: omg}现在让我们来看一下我们可以在映射上使用的一些属性。
示例
考虑以下示例:
void main() {
var colors = new Map();
colors['blue'] = true;
colors['red'] = false;
colors['green'] = false;
colors['yellow'] = true;
colors[1] = "omg";
print(colors['blue']); // accessing a specific key
print(colors.length); // checking the number of key-value pairs present in the map
print(colors.isEmpty); // checking if the map is empty or not
print(colors.keys); // printing all the keys present in the map
print(colors);
}输出
true
5
false
(blue, red, green, yellow, 1)
{blue: true, red: false, green: false, yellow: true, 1: omg}我们还可以使用for-in循环迭代映射中存在的键和值。
示例
考虑以下示例:
void main() {
var colors = new Map();
colors['blue'] = true;
colors['red'] = false;
colors['green'] = false;
colors['yellow'] = true;
colors[1] = "omg";void main() {
var colors = new Map();
colors['blue'] = true;
colors['red'] = false;
colors['green'] = false;
colors['yellow'] = true;
colors[1] = "omg";
print(" ---- Keys ---- ");
for(var key in colors.keys){
print(key);
}
print(" ---- Values ---- ");
for(var value in colors.values){
print(value);
}
}
print(" ---- Keys ---- ");
for(var key in colors.keys){
print(key);
}
print(" ---- Values ---- ");
for(var value in colors.values){
print(value);
}
}输出
---- Keys ---- blue red green yellow 1 ---- Values ---- true false false true omg
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP