我有一个带有覆盖的clone()
方法的对象数组。当我使用arraycopy()
函数时,它将通过clone()
方法复制每个元素还是进行浅表复制?
谢谢
最佳答案
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
如果您确实要复制对象本身,则必须手动执行此操作。如果对象是
Cloneable
,则应执行简单的for循环:Person[] copy = new Person[people.length];
for(int i = 0; i < people.length; ++i) copy[i] = people[i].clone();
自Java 8起提供了另一个也许更优雅的解决方案:
Person[] copy = Arrays.stream(people).map(Person::clone).toArray(Person[]::new);