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.