在Java中使用clone()
是一个棘手的问题1,2.实际上,clone()
是一个复制构造函数,为此,Dart List
、Map
和Set
类型都有一个名为.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个