可以说我有下面的代码:Java奇怪的引用行为?
public class Collection implements CollectionInterface{
ElementInterface[] elementArray = new ElementInterface[100];
int amountOfElements = 0;
public Collection()
{
}
public Collection(CollectionInterface collection)
{
CollectionInterface tempCollection = new Collection();
while(!collection.isEmpty())
{
ElementInterface element = collection.Remove().clone();
tempCollection.Add(element.clone2());
elementArray[amountOfElements++] = element;
}
collection = tempCollection;
}
public void Add(ElementInterface element){
elementArray[amountOfElements++] = element;
}
public ElementInterface Remove(){
ElementInterface element = elementArray[amountOfElements].clone2();
elementArray[amountOfElements] = null;
amountOfElements--;
return element;
}
public boolean isEmpty(){
return amountOfElements == 0;
}
public CollectionInterface clone()
{
return new Collection(this);
}
}
还好吧,这似乎有点奇怪,它是。但如果我使用以下代码:
CollectionInterface collection = new Collection();
collection.Add(new Element("Foo"));
collection.Add(new Element("Bar"));
CollectionInterface collection2 = collection.clone();
第一个不包含任何元素了。这怎么可能?
如果你真的认为是Java,就不要说JavaScript(它们没有任何共同之处)。 – helpermethod
...请给*真正的*代码,而不是代码,这相当明显不会编译。 –
我说JavaScript吗?我不是故意的?也许autocompletion做到了?我不确定,对不起。还有Upvoted Jon Skeet,你是绝对正确的。我正在编辑它,但你太快了! –