2015-04-01 32 views
-1

我有一個覆蓋clone()方法的對象數組。當我使用arraycopy()函數時,它是否會通過clone()方法複製每個元素,或者它會生成一個淺度副本? 謝謝System.arraycopy是否使用clone()方法?

+4

它會引用剛纔複製的對象,而不是:

Person[] copy = new Person[people.length]; for(int i = 0; i < people.length; ++i) copy[i] = people[i].clone(); 

另一個,也許更優雅的解決方案,因爲Java的8提供對象本身。 – isnot2bad 2015-04-01 23:12:54

回答

1

Both,System.arraycopy(...)以及Arrays.copyOf(...)只是創建原始數組的一個(淺)副本;他們不會自己複製或克隆包含的對象:

// given: three Person objects, fred, tom and susan 
Person[] people = new Person[] { fred, tom, susan }; 
Person[] copy = Arrays.copyOf(people, people.length); 
// true: people[i] == copy[i] for i = 0..2 

如果您確實想要自己複製對象,則必須手動執行此操作。一個簡單的for循環應該做的,如果對象是Cloneable

Person[] copy = Arrays.stream(people).map(Person::clone).toArray(Person[]::new); 
3

System.arraycopy會生成指定數組部分的淺表副本。

+0

那麼'for'循環是深拷貝的唯一途徑? – 2015-04-01 23:16:07

+0

通過爲數組的元素類型提供複製構造函數,您可以使用'java.util.Arrays.stream(objs).map(T :: new).toArray(T [] :: new)'創建一組深度複製 – muued 2015-04-01 23:25:02

相關問題