可以說我有下面的代碼: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,你是絕對正確的。我正在編輯它,但你太快了! –