我的代码如下所示:
public class Polynomial {
List<Term> term = new LinkedList<Term>();
并且似乎每当我做类似 的事情时term.add(anotherTerm)
, anotherTerm 是......另一个 Term 对象,似乎 anotherTerm 引用的内容与我刚刚插入 term 的内容相同,因此每当我尝试更改 anotherTerm 时,term.get( 2)(比方说)get也变了。
我怎样才能防止这种情况发生?
由于请求了代码:
//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);
}
调用插入方法的代码:
poly.insert(anotherTerm);
创建 anotherTerm 术语的代码:
Term anotherTerm = new Term(3, 7.6); //sets coefficient and power to 3 and 7.6
调用插入方法的新代码:
poly.insert((Term)anotherTerm.clone());
clone() has protected access in java.lang.Object
不幸的是,即使在做了之后,它仍然不起作用public class Term implements Cloneable{