Use of clone()
in Java is tricky and questionable1,2. Effectively, clone()
is a copy constructor and for that, the Dart List
, Map
and Set
types each have a named constructor https://www.dartlang.org/docs/dart-up-and-running/contents/ch02.html#ch02-constructors-named named .from()
that perform a shallow copy https://stackoverflow.com/questions/184710/what-is-the-difference-between-a-deep-copy-and-a-shallow-copy; e.g. given these declarations
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() https://api.dartlang.org/apidocs/channels/stable/#dart-dom-html.Node@id_clone method.
1 J. Bloch, "Effective Java" 2nd Ed., Item 11.
2 B. Venners, "Josh Bloch on Design: Copy Constructor versus Cloning", 2002 http://www.artima.com/intv/bloch13.html. Referenced from here3. Quote from the article:
如果你读过我书中有关克隆的内容,特别是如果你读到字里行间的内容,你就会知道我认为克隆已经被彻底破坏了。 ---J·布洛赫
3 Dart Issue #6459, clone instance(object) https://code.google.com/p/dart/issues/detail?id=6459.