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

更新於:2021年5月21日

400 次瀏覽

開啟你的職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.