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;
}
}
}