我有这样的代码:
public class Polynomial {
List<Term> term = new LinkedList<Term>();
似乎每当我做类似term.add(anotherTerm)
的事情时,anotherTerm 是...另一个 Term 对象,似乎 anotherTerm 引用的是与我刚刚引用的相同的东西插入到术语中,这样每当我尝试更改另一个术语时,term.get(2)(比方说)也被更改了。
如何防止这种情况发生?
由于请求代码:
//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);
创建另一个术语的代码:
Term anotherTerm = new Term(3, 7.6); //sets coefficient and power to 3 and 7.6
调用插入方法的新代码:
poly.insert((Term)anotherTerm.clone());
不幸的是,由于 clone() 在 java.lang.Object 中具有 protected 访问
,即使在执行了 public class Term implements Cloneable{
之后,这仍然无法正常工作。 p>
最佳答案
解决方案很简单:使 Term
不可变。
Effective Java 2nd Edition,第 15 条:最小化可变性:
- Immutable objects are simple.
- Immutable objects can be shared freely.
- Immutable objects make great building blocks for other objects.
- Classes should be immutable unless there's a very good reason to make them mutable.
- If a class cannot be made immutable, limit its mutability as much as possible.
- Make every field
final
unless there is a compelling reason to make it non-final
像 Term
这样简单和小的东西真的应该是不可变的。这是一个更好的整体设计,您不必担心您在问题中提出的问题。
另见
这个建议变得更有说服力,因为其他答案都建议您使用 clone()
。
Effective Java 2nd Edition,第 11 条:明智地覆盖clone
Because of the many shortcomings, some expert programmers simply choose to never override the
clone
method and never invoke it except, perhaps, to copy arrays.
来自 interview with author Josh Bloch :
If you've read the item about cloning in my book, especially if you read between the lines, you will know that I think
clone
is deeply broken.
不要使Term implements Cloneable
。改为使其不可变。
另见
关于java - LinkedList 插入绑定(bind)到插入的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2779067/