gpt4 book ai didi

collections - 在 Dart 中克​​隆列表、 map 或集合

转载 作者:行者123 更新时间:2023-12-03 08:24:31 33 4
gpt4 key购买 nike

来自 Java 背景:“克隆”Dart 的推荐方法是什么 List , MapSet ?

最佳答案

使用 clone()在 Java 中是棘手和有问题的1,2。有效,clone()是一个复制构造函数,为此,Dart List , MapSet每个类型都有一个 named constructor命名 .from()执行 shallow copy ;例如鉴于这些声明

  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”第 2 版,第 11 项。
2 B. Venners, "Josh Bloch on Design: Copy Constructor versus Cloning", 2002 .引用自here3。引自文章:

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) .

关于collections - 在 Dart 中克​​隆列表、 map 或集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21744480/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com