0

I've this Java generic class, and I'd like to clone it, in order to perform a deep copy of it. Now, I thought this following code would work, but in the clone() method I cannot call clone() for every member which is not a primitive type. I tried to require the parameters to implement the Cloneable interface, but id doesn't work yet, it fails calling [first/second].clone().

I would appreciate any suggestions. Thanks in advance.

[here's the code]

public class Pair<F extends Cloneable, S extends Cloneable> implements Cloneable {

    private F first;
    private S second;

    public Pair(F a, S b) {

        first = a;
        second = b;
    }

    public F getFirst() {
        return first;
    }

    public S getSecond() {
        return second;
    }

    public void setFirst(F first) {
        this.first = first;
    }

    public void setSecond(S second) {
        this.second = second;
    }

    @Override
    public String toString() {
        return "["+first+", "+second+"]";
    }

    @Override
    public boolean equals(Object o) {

        if(o == null)   return false;
        if(o == this)   return true;
        if(!getClass().getName().equals(o.getClass().getName()))    return false;

        Pair ref = (Pair)o;

        return first.equals(ref.first) && second.equals(ref.second);
    }

    @Override
    public int hashCode() {
        int hash = 7;
        hash = 61 * hash + Objects.hashCode(this.first);
        hash = 61 * hash + Objects.hashCode(this.second);
        return hash;
    }

    @Override
    public Object clone() {

        try {

            Pair<F, S> cloned = (Pair<F, S>)super.clone();

            cloned.first = (F)first.clone();
            cloned.second = (S)second.clone();

            return cloned;
        }
        catch(CloneNotSupportedException e) {
            return null;
        }
    }

}
eToTheEcs
  • 1
  • 1
  • 1
    When you say " it fails calling [first/second].clone()", what exactly is the failure? A compile error? An exception? Can you tell us the text of the error? – Dawood ibn Kareem May 10 '18 at 21:33
  • 2
    Be aware that `Clonable` is [broken](https://stackoverflow.com/questions/2326758/how-to-properly-override-clone-method). – M. le Rutte May 10 '18 at 21:36
  • 1
    it gives me a compile-time error, saying that there's not available implementation of the method clone() – eToTheEcs May 10 '18 at 22:03
  • Can you post the code for one of the classes you're using for First and Second if you are using classes you've created yourself. – Thatalent May 11 '18 at 11:38

1 Answers1

0

Unfortunately, there is no common interface or supertype in Java for objects with a public .clone() method. You could create your own interface that does this, but only your own classes would potentially implement this interface, so it would still not work for system classes that may have a public .clone() method.

newacct
  • 119,665
  • 29
  • 163
  • 224