有没有办法在 O(1) 中将 ArrayList 的全部内容移动到另一个 ArrayList 实例?
即:只有对支持数组的引用从一个实例传递到另一个实例(元素不会一个一个地复制)。
例如:
ArrayList<String> a = new ArrayList<>(Arrays.asList("A", "B", "C"));
ArrayList<String> b = new ArrayList<>();
a.moveContentsTo(b);
// 'a' is now empty, while 'b' contains everything that 'a' did before and 'a != b'
// It is desired that the 'moveContentsTo' method is O(1)
更好的是,有ArrayList#swapContents(ArrayList)
什么方法吗?
进一步的解释和用例:
进一步解释1:'a'和'b'的引用不能互换。我不是在寻找tmp = a; a = b; b = tmp;
解决方案的类型。
进一步解释2:运算必须及时~O(1)。
用例:当对象想要封装外部构造的列表时,这很有用:
public class A {
private ArrayList<String> items = new ArrayList<>();
/**
* This method takes the sole ownership of the contents. Whoever
* passed the list from the outside will not be able to modify
* contents of 'this.items' from outside the class.
*/
public AnImmutableObject(ArrayList<String> items) {
if (items != null) {
items.moveContentsTo(this.items);
}
}
/**
* Other collections that do not provide the 'move' functionality
* must be copied. If we just stored the reference to 'items' we
* would break encapsulation as whoever called the constructor
* still have write capabilities to the collection.
*/
public A(Collection<String> items) {
if (items != null) {
this.items.addAll(items);
}
}
public List<String> getItems() {
return Collections.unmodifiableList(items);
}
}
请注意,我们希望避免进行复制(以提高速度并减少内存使用)。关键是被调用者必须失去修改(现在封装的)的能力ArrayList
。