来自Java背景:推荐的"克隆"DART ListMapSet的方式是什么?

推荐答案

在Java中使用clone()是一个棘手的问题1,2.实际上,clone()是一个复制构造函数,为此,Dart ListMapSet类型都有一个名为.from()named constructor,用于执行shallow copy;e、 g.鉴于这些声明

  Map<String, int> numMoons, moreMoons;
  numMoons = const <String,int>{ 'Mars' : 2, 'Jupiter' : 27 };
  List<String> planets, morePlanets;

你可以这样使用.from():

  moreMoons = new Map<String,int>.from(numMoons)
    ..addAll({'Saturn' : 53 });
  planets = new List<String>.from(numMoons.keys);
  morePlanets = new List<String>.from(planets)
    ..add('Pluto');

请注意,List.from()通常接受迭代器,而不仅仅是List.

为完整起见,我应该提一下,dart:html Node类定义了一个clone()方法.


1 J. Bloch, "Effective Java" 2nd Ed., Item 11.
2 B. Venners, "Josh Bloch on Design: Copy Constructor versus Cloning", 2002. Referenced from here3. Quote from the article:

If you've read the item about cloning in my book, especially if you read between the lines, you will know that I think clone is deeply broken. ---J.Bloch

3 Dart Issue #6459, clone instance(object).

Dart相关问答推荐

如何在 Dart 2.17+ 中处理future 的枚举值

有没有可能用Flatter摄像头插件播放视频?

停止音频循环(audioplayers 包)

在 Dart 中向服务器发出多个独立请求的最佳方式

Expansion Panel底部溢出

不推荐使用AnteStorStateofType,请改用findAncestorStateOfType

设置Dart中非常量的默认值

将DateTime转换为ISO 8601

dart和下划线

在 Dart 中使用固定长度列表有性能优势吗?

错误:default constructor is already defined

Dart 转换列表的每个元素

Dart:如何判断变量类型是否为字符串

如何在抽象类中声明工厂构造函数?

我如何知道 websockets 的连接是否有效?

如何在 Ubuntu 网络服务器上为 Dart 安装 pub(命令行使用)

将多张map合并/合并为一张map

在 Dart 中,bool是否有parse,就像int一样?

如何在 Dart 中引用另一个文件?

Dart 会支持使用现有的 JavaScript 库吗?