有人知道 List 复制 impl 只在变异时才真正进行复制吗?对于以读取为主的用例,它(编辑:可能)比 new ArrayList<>(oldList)
更有效。 。会像 CopyOnWriteArrayList
只是它只会复制元素零次或一次。
示例:
List list = Lists.lazyCopy(oldList); // no copy
list.get(0); // delegate to oldList
list.set(0, null); // make a copy, mutate the copy
list.get(0); // read from copy
list.set(0, null); // mutate the copy, don't copy again
最佳答案
正如您在评论中提到的,您有一个 com.google.common.collect.ImmutableList
:为什么不使用简单的 java.util.concurrent.CopyOnWriteArrayList
与你的 ImmutableList ?
CopyOnWriteArrayList(Collection<? extends E> c)
simply uses the source collection's toArray
method创建 CopyOnWriteArrayList 的支持数组。以及toArray
的非单例、非空RegularImmutableList的实现也只是one System.arraycopy从它自己的支持数组到一个新数组。因此,只有一个内存大分配用于新的后备数组和 System.arraycopy,无论哪种情况,whosh 都应该相当快。当然,缺点是重复的后备数组会增加内存使用量。
关于java - 惰性列表复制(写入时复制),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13349226/