简体   繁体   中英

Difference between initiliazing an object and super.clone()

I am taking data structure course and I am trying to code a DoublyLinked list and its own method.In my book I saw this code.Is there any difference between code (1) and code (2). If it does, which one should I use?

DoublyLinkedList<E> other=(DoublyLinkedList<E>) super.clone(); //code (1)

DoublyLinkedList<E> other=new DoublyLinkedList<>();//code (2)

It depend what is write in implementation constructor of DoublyLinkedList and method "clone" of super class. You can do it differently or equally.

If you use implement "List", you must write own method clone. "LincedList" has own method.

And read if you want this article: Java Cloning: Copy Constructors vs. Cloning 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));
    }
}

Results:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 2, 4, 6, 8]
true

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM