有没有办法在 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;一 = 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
的能力。
最佳答案
@Lirik 的回答很棒 +1。但是,如果您正在寻找真正的 ArrayList#swapContents(ArrayList)
,可以按照以下方法进行操作:
public static void swapContents(ArrayList<String> listA, ArrayList<String> listB)
{
List<String> temp = new ArrayList<String>(listA);
listA.clear();
listA.addAll(listB);
listB.clear();
listB.addAll(temp);
}
关于java - 如何将一个 ArrayList 的内容移动到另一个?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10022441/