在Dart中克隆列表,地图或集合 [英] Clone a List, Map or Set in Dart

查看:156
本文介绍了在Dart中克隆列表,地图或集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

来自Java背景:建议如何克隆一个Dart List Map 设置 c>使用克隆() )在Java是棘手和有问题的 1,2 。有效地, clone()是一个复制构造函数,为此,Dart List Map 设置类型都有命名为 .from()的命名构造函数,它们执行允许复制;例如给定这些声明

  Map< String,int& numMoons,moreMoons; 
numMoons = const< String,int> {'Mars':2,'Jupiter':27};
List< String>行星,更多

您可以使用 .from() this:

  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



为了完整起见, c $ c> dart:html Node 类定义 clone()方法。






sup> 1 J. Bloch, Effective Java 第二版,第11项。

2 B。 Venners, Josh Bloch on Design:Copy Constructor versus Cloning ,2002 。从这里引用 3

如果您在我的书中阅读过有关克隆的项目,特别是如果你在线之间阅读,你会知道我认为克隆被深深打破了。 --- J.Bloch



3 a href =https://code.google.com/p/dart/issues/detail?id=6459> Dart Issue#6459,clone instance(object)。


Coming from a Java background: what is the recommended way to "clone" a Dart List, Map and Set?

解决方案

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 named .from() that perform 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;

you can use .from() like this:

  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');

Note that List.from() more generally accepts an iterator rather than just a List.

For sake of completeness, I should mention that the dart:html Node class defines a clone() method.


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中克隆列表,地图或集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆