专业的JAVA编程教程与资源

网站首页 > java教程 正文

Dart编程学习笔记05-列表与映射表

temp10 2025-08-02 21:41:40 java教程 3 ℃ 0 评论

本章节中,列表相当于C语言中的数组,只不过比数组更加灵活一些,映射基本就是键值那一套,方便JOSN协议组包与解包,下面直接上例子。

一 代码

Dart编程学习笔记05-列表与映射表

void main() async
{
  //创建数据列表
  List listMonth = ['jan','feb','mar'];
  listMonth.add('april');
  listMonth.forEach(print);
  //创建复杂的数据类型
  Map<String,dynamic> filmStarWars = {"title":"star wars","year":1977}; 
  Map<String,dynamic> filmEmpire   = {"title":"The Empire Strikes"};
  Map<String,dynamic> filmJedi     = {"title":"The Return of the Jedi"};

  List listFilms = [filmStarWars,filmEmpire,filmJedi];
  Map<String,dynamic> currentFilm = listFilms[0];

  print(currentFilm);
  print(currentFilm['title']);
  //处理映射表的键/值
  Map<int,String> MapMonths = {0:'jan',1:'Feb',2:'March'};
  Map<int,String> moreMonth = {3:'april',4:'May'};

  MapMonths.addEntries(moreMonth.entries);

  MapMonths.forEach((key,value)
  {
    print('$key,$value');
  });

  //打印映射表数据结构的内容
  print("Month:${MapMonths[0]}");
  print("Map: $MapMonths");

  //验证映射表中是否存在内容
  if(MapMonths[0] != null)
  {
    print('Test 1: Key exist');
  }

  if(MapMonths.containsKey(2))
  {
    print('Test 2: Key exist');
  }
  //打印复杂的数据类型
  Map<String,dynamic> data = 
  {
    jsonEncode('title'):json.encode('Star Wars'),
    jsonEncode('year'):json.encode(1977)
  };
  
  Map<String,dynamic> items = json.decode(data.toString());

  print(items);
  print(items['title']);
  print("this is the title:$items['title']");
  print('this is the title:${items['title']}');

}

二 列表与映射表的用途

2.1 列表(List)

用途:

存储有序的元素集合

当需要按索引访问元素时

保持元素的插入顺序

允许重复元素

2.2映射表(Map)

用途:

存储键值对(key-value pairs)

通过键快速查找值

键必须是唯一的

不保证元素的顺序(除非使用LinkedHashMap)

三 总结

特性

列表(List)

映射表(Map)

存储方式

有序元素集合

键值对集合

访问方式

通过索引(数字)

通过键(任意类型)

元素顺序

保持插入顺序

默认不保证顺序

重复

允许重复元素

键必须唯一,值可重复

典型用途

有序数据集合

字典/关联数组/查找表

选择使用哪种集合类型取决于你的具体需求:如果需要有序且可能重复的元素集合,使用List;如果需要通过键快速查找值,使用Map。

Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表