且构网

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

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

更新时间:2023-11-27 22:26:22

这应该这样做:

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?

它也谨慎地指出,因为在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).

鉴于上述说法,那么如果从阵列 A 来阵列 B 在Java中,两个数组复制的东西将引用相同的数据。所有你在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. 

移动语义的作用:

Move semantics does:

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

您救一个自毁,但只能在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