[英]Difference between initiliazing an object and super.clone()
我正在上數據結構課程,嘗試編寫一個DoublyLinked列表及其自己的方法,在我的書中我看到了這段代碼,代碼(1)和代碼(2)之間是否有任何區別。 如果可以,我應該使用哪一個?
DoublyLinkedList<E> other=(DoublyLinkedList<E>) super.clone(); //code (1)
DoublyLinkedList<E> other=new DoublyLinkedList<>();//code (2)
它取決於在DoublyLinkedList的實現構造函數中寫入的內容以及超類的方法“ clone”。 您可以不同地或同等地做。
如果使用工具“列表”,則必須編寫自己的方法克隆。 “ LincedList”具有自己的方法。
並閱讀是否需要這篇文章:Java克隆:復制構造函數與克隆https://dzone.com/articles/java-cloning-copy-constructor-vs-cloning
import java.util.ArrayList;
import java.util.stream.IntStream;
public class Clonetest implements Cloneable{
ArrayList<Integer> ints = new ArrayList<>();
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
public static void main(String[] args) throws CloneNotSupportedException {
Clonetest clA = new Clonetest();
IntStream.range(0,10).forEach(value -> clA.ints.add(value)); //add Integers
System.out.println(clA.ints);
clA.ints.removeIf(integer -> integer % 2 > 0); //remove part in clA.ints
Clonetest clB = (Clonetest) clA.clone();
System.out.println(clB.ints);
System.out.println(clB.ints.equals(clA.ints));
}
}
結果:
[0、1、2、3、4、5、6、7、8、9]
[0,2,4,6,8]
真正
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.