javalinked-listimmutabilitycloningdefensive-copy

LinkedList insert tied to inserted object


I have code that looks like this:

public class Polynomial {
    List<Term> term = new LinkedList<Term>();

and it seems that whenever I do something like term.add(anotherTerm), with anotherTerm being... another Term object, it seems anotherTerm is referencing the same thing as what I've just inserted into term so that whenever I try to change anotherTerm, term.get(2) (let's say) get's changed too.

How can I prevent this from happening?

Since code was requested:

//since I was lazy and didn't want to go through the extra step of Polynomial.term.add
public void insert(Term inserting) {
    term.add(inserting);
}

Code calling the insert method:

poly.insert(anotherTerm);

Code creating the anotherTerm Term:

Term anotherTerm = new Term(3, 7.6); //sets coefficient and power to 3 and 7.6

New code calling the insert method:

poly.insert((Term)anotherTerm.clone());

Which unfortunately still doesn't work due to clone() has protected access in java.lang.Object, even after doing public class Term implements Cloneable{


Solution

  • OK, replacing my old answer with this, now that I understand the question and behavior better.

    You can do this if you like:

    public void insertTerm(Term term) {
        polynomial.insert(new Term(term));
    }
    

    and then create a new Term constructor like this:

    public Term(Term term) {
        this.coefficient = term.coefficient;
        this.exponent = term.exponent;
    }
    

    That should work.