经过研究,我了解到,当使用另一个列表中的值设置一个列表时,只会复制引用,而不是实际值。
最初,我想创建一个包含原始列表值的精确副本的列表。然后,在对原始列表执行了一些操作之后,我希望能够将值从复制列表复制回原始列表。
到目前为止,我找不到解决方案,该解决方案没有将副本列表中的值设置为与原始列表中的新值相同。
下面的代码显示了我要执行的逻辑,但是找不到合适的“功能”来创建列表的“克隆”。
class NumPairs {
NumPairs({this.first, this.second});
int first;
int second;
}
main() {
List<NumPairs> from = [
NumPairs(
first: 1,
second: 2,
),
NumPairs(
first: 2,
second: 1,
),
];
List<NumPairs> to = [];
to = from;
print('${to[0].first} ' + '${to[0].second} ' + ' inital TO');
print('${from[0].first} ' + '${from[0].second} ' + ' inital FROM');
to[0].first = 0;
to[0].second = 0;
print('${to[0].first} ' + '${to[0].second} ' + ' after zeroed TO = 0');
print(
'${from[0].first} ' + '${from[0].second} ' + ' FROM after TO is zeroed');
to = from;
print('${to[0].first} ' +
'${to[0].second} ' +
' after trying to copy to from FROM');
}
输出:
1 2 inital TO
1 2 inital FROM
0 0 after zeroed TO = 0
0 0 FROM after TO is zeroed
0 0 after trying to copy to from FROM
答案 0 :(得分:1)
听起来像您希望能够克隆原始列表中的对象的声音。可以按照以下步骤进行。
mkdir -p .../bin
在其中添加了命名构造函数“ clone”的地方。
现在您可以使用以下方法克隆原始列表:
class NumPairs {
NumPairs({this.first, this.second});
int first;
int second;
NumPairs.clone(NumPairs numpairs): this(first: numpairs.first, second: numpairs.second);
}
原始代码如下。
List<NumPairs> to = from.map((elem)=>NumPairs.clone(elem)).toList();
结果
class NumPairs {
NumPairs({this.first, this.second});
int first;
int second;
NumPairs.clone(NumPairs numpairs): this(first: numpairs.first, second: numpairs.second);
}
main() {
List<NumPairs> from = [
NumPairs(
first: 1,
second: 2,
),
NumPairs(
first: 2,
second: 1,
),
];
//to = from;
// Gets replaced with the following which clones the 'from' list
List<NumPairs> to = from.map((elem)=>NumPairs.clone(elem)).toList();
print('${to[0].first} ' + '${to[0].second} ' + ' inital TO');
print('${from[0].first} ' + '${from[0].second} ' + ' inital FROM');
to[0].first = 0;
to[0].second = 0;
print('${to[0].first} ' + '${to[0].second} ' + ' after zeroed TO = 0');
print(
'${from[0].first} ' + '${from[0].second} ' + ' FROM after TO is zeroed');
to = from;
print('${to[0].first} ' +
'${to[0].second} ' +
' after trying to copy to from FROM');
}