Why is clone () not working as expected?

Having the following code in java

public Polynomial multiply(Polynomial aPolynomial){
    Polynomial ret = new Polynomial();
    for (Tuple i: this.pol){
        Polynomial temp = aPolynomial.clone();
        System.out.print(temp);
        for (Tuple j: temp.pol){
            j.setCoef(j.getCoef() * i.getCoef());
            j.setPower(j.getPower() + i.getPower());
        }
        ret = ret.add(temp).clone();
    }       
    return ret;
}

I get as output for System.out.print(temp)always different values. That means aPolynomialchanging somewhere at runtime.

Change Polynomial temp = aPolynomial.clone();to:

LinkedList<Tuple> list1 = (LinkedList<Tuple>) aPolynomial.pol.clone();
Polynomial temp = new Polynomial(list1);

doesn't help either for the output to System.out.print(temp)be different every time the loop starts.

Where is my mistake?

Edit:

public Polynomial clone() {
    try {
        return (Polynomial)super.clone();
    } catch (CloneNotSupportedException e) {
        e.printStackTrace();
    }
    return null;
}

print hashCode() tempand aPolynomialleads to two different values.

aPolynomialhas the same hashCodein every run of the cycle for.

answers some questions in the comments:

since it’s Polynomialnot inherited anywhere, as far as I am interested I super.clone()will refer toObject

I have my own method toString.

+4
2

, , , : , temp, aPolynomial, . , , temp.pol. clone Polynomial, aPolynomial temp pol.

- clone(), pol Polynomial.

- :

public Polynomial clone() {
    try {
        Polynomial p = (Polynomial)super.clone();
        p.pol = this.pol.clone();
        return p;
    } catch (CloneNotSupportedException e) {
        e.printStackTrace();
    }
    return null;
}
+6

, Java Object # clone() . , ( "x.clone()!= X" ), . , , , . , . , .

(), ( , , ). .

, clone() , ( Google, Bloch clone() ). ( , , , , ) . , .

@Edit: - , http://www.artima.com/intv/bloch13.html. Java 2nd Edition

+3

All Articles