首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将常量列表变量赋给非常数列表变量并对其进行修改

将常量列表变量赋给非常数列表变量并对其进行修改
EN

Stack Overflow用户
提问于 2021-11-10 12:41:55
回答 1查看 43关注 0票数 1

我已经创建了一个常量列表变量,我想把它放到一个新的列表变量中,并修改它的项。但是我得到了一个错误Unhandled Exception: Unsupported operation: Cannot remove from an unmodifiable list

代码语言:javascript
复制
const List<String> constantList = [
  'apple',
  'orange',
  'banana'
];

List<String> newList = [];
newList= constantList;
newList.remove('banana');
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-11-10 12:49:40

对象的常量在对象上,而不是在变量上。所以即使你改变了变量的类型,对象仍然是const。

您的示例中有一个问题:

代码语言:javascript
复制
List<String> newList = [];
newList= constantList;

这并不是你想的那样。它实际做的是创建一个新的空列表,并使用newList来指向这个新列表。

然后将newList更改为指向constantList所指向的list实例。所以在这段代码完成之后,newListconstantList指向相同的常量列表对象。

如果您想复制constantList引用的列表,可以执行以下操作:

代码语言:javascript
复制
void main() {
  const List<String> constantList = ['apple', 'orange', 'banana'];
  List<String> newList = constantList.toList();
  // Alternative: List<String> newList = [...constantList];
  newList.remove('banana');
  print(newList); // [apple, orange]
}

此外,您还可以尝试使用.addAll()

代码语言:javascript
复制
void main(List<String> args) {
  const List<String> constantList = ['apple', 'orange', 'banana'];

  List<String> newList = [];
  newList.addAll(constantList);
  newList.remove('banana');
  print(newList); //[apple, orange]
}

此副本不是常量列表,因此可以进行操作。

有关pass-by-reference的更多信息

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69913447

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档