且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将一个 ArrayList 的内容移动到另一个?

更新时间:2023-11-27 23:00:46

应该这样做:

ArrayList<String> a = new ArrayList<>(Arrays.asList("A", "B", "C"));
ArrayList<String> b = a;
a = new ArrayList<>();

从概念上讲,a 现在是空的,b 包含之前包含的 a .有一个单一的分配,没有数据的复制,这是你能做到的最快的.这是否满足您的要求,或者您是否真的希望 a 仍然引用相同的数组,只是给定的数组现在应该是空的?

Conceptually speaking, a is now empty and b contains what a contained before. There was a single assignment and no copying of data, which is about the fastest you can do it. Does that satisfy your requirement, or do you actually want a to still reference the same array except that the given array should now be empty?

我也不相信在 C++ 中移动操作的时间复杂度是 O(1). 指出因为 Java 中的类使用引用语义,有这些语言中从来没有任何对象的隐式副本.移动语义解决的问题在 Java 中不存在,也从未存在过."(参见 FredOverflow 的回答:C++ 右值引用和移动语义)

I don't believe that in C++ the time complexity for the move operation is O(1) either. It's also prudent to point out that "because classes in Java use reference semantics, there are never any implicit copies of objects in those languages. The problem move semantics solve does not and has never existed in Java." (see the answer by FredOverflow: C++ Rvalue references and move semantics)

有没有一种方法可以将一个 ArrayList 的全部内容移动到另一个 ArrayList 中,以便只有对后备数组的引用从一个传递到另一个(即,元素不会被一个一个地复制).

Is there a way to move the entire contents of an ArrayList to another ArrayList so that only the reference to the backing array is passed from one to the other (i.e., so that elements are not copied one by one).

给定上面的语句,那么如果你在 Java 中从数组 a 复制一些东西到数组 b,两个数组将引用相同的数据.在 C++ 中使用移动语义所做的一切就是保存需要创建的临时对象,以便进行这样的复制:

Given the above statement, then if you copy something from array a to array b in Java, both arrays will reference the same data. All that you do with move semantics in C++ is that you save the temporary object which needs to be created in order to make such a copy:

X foo();
X x;
// perhaps use x in various ways
x = foo();

最后一个:

destructs the resource held by x,
clones the resource from the temporary returned by foo,
destructs the temporary and thereby releases its resource. 

移动语义:

swap resource pointers (handles) between x and the temporary,
temporary's destructor destruct x's original resource.

你省了一个destruct,但只在C++中……上面的问题在Java中不存在!有关移动语义的更多详细信息,请参阅本文:http://thbecker.net/articles/rvalue_references/section_02.html

You save one destruct, but only in C++... the above problem does not exist in Java! See this article for more details on move semantics: http://thbecker.net/articles/rvalue_references/section_02.html