简体   繁体   English

"有没有办法将不可变列表转换为可变列表?"

[英]is there a way to convert an immutable list to a mutable one?

So I wanted to create a method to add an element into an immutable list but I kinda need it to be a mutable list to be returned at the end.所以我想创建一个方法来将元素添加到不可变列表中,但我有点需要它是一个可变列表,以便在最后返回。 So far, I have have created a mutable copy of the immutable list:到目前为止,我已经创建了不可变列表的可变副本:

Grid2D add(int elem) {
          List<Integer> newlist = new ArrayList<Integer>();
          for (int i = 0; i < this.list.size(); i++) {
              newlist.add(list.get(i));
          }   
          newlist.add(elem);
          return new Grid2D(newlist, this.numOfCols);
}   

Is there a way to convert an immutable list to a mutable one?有没有办法将不可变列表转换为可变列表?

<\/blockquote>

The short answer is that there isn't a way.简短的回答是没有办法。

The long answer is that it depends what you mean by "convert" to mutable.长答案是,这取决于您将“转换”为可变的意思。

Obviously, you can create a mutable copy of an immutable list 1<\/sup> .显然,您可以创建不可变列表1<\/sup>的可变副本。 But the downside is that the mutable list is a distinct list.但缺点是可变列表是一个不同的列表。 Changes made to the immutable list after you made the copy are not reflected in the new list.复制后对不可变列表所做的更改不会反映在新列表中。 And vice-versa.反之亦然。

If you were to "crack open" the immutable list abstraction, it may be<\/em> possible to mutate it.如果您要“破解”不可变列表抽象,则可能会对其<\/em>进行变异。 (Nasty reflection is involved, and you need to know how the specific immutable list class has been implemented.) But this is a really bad idea. (涉及到令人讨厌的反射,你需要知道具体的不可变列表类是如何实现的。)但这是一个非常糟糕的主意。 Various parts of your application code-base will be assuming that the immutable collection is immutable.您的应用程序代码库的各个部分将假设不可变集合是不可变的。 Violating the invariant could make all sorts of things behave incorrectly.违反不变量可能会使各种事情的行为不正确。

Finally, if the "immutable list" was originally created using Collections.unmodifiableList<\/code> , it is not strictly immutable.最后,如果“不可变列表”最初是使用Collections.unmodifiableList<\/code>创建的,则它不是严格不可变的。 You could potentially modify it by modifying the original list that was wrapped by the unmodifiableList<\/code> call.您可以通过修改由unmodifiableList<\/code>调用包装的原始列表来修改它。


1 - You don't necessarily need to use ArrayList<\/code> for this.<\/sup> 1 - 您不一定需要为此使用ArrayList<\/code> 。<\/sup> You could use any List<\/code> implementation class, including a custom implementation that you wrote from scratch.<\/sup>您可以使用任何List<\/code>实现类,包括您从头开始编写的自定义实现。<\/sup> But you do<\/em> need to use new<\/code> to create a new List<\/code> instance.<\/sup>但是您确实<\/em>需要使用new<\/code>来创建一个新的List<\/code>实例。<\/sup>

"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM