Lets say I have the following code:
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);
}
}
Allright, it might seem a bit strange, and it is. But if I use the following code:
CollectionInterface collection = new Collection();
collection.Add(new Element("Foo"));
collection.Add(new Element("Bar"));
CollectionInterface collection2 = collection.clone();
The first one doesn’t contain any elements anymore. How is that possible?
You can not change the reference of an input parameter, as you try in the second constructor.
a) is this a syntax error,
b)
collectionis a local variable; assigning to it will change nothing on the outside of the constructor.