gpt4 book ai didi

Java 奇怪的引用行为?

转载 作者:行者123 更新时间:2023-12-01 19:11:46 24 4
gpt4 key购买 nike

假设我有以下代码:

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();

第一个不再包含任何元素。这怎么可能?

最佳答案

这很有道理。在由 clone() 调用并以原始集合作为参数的构造函数中,您可以使用:

ElementInterface element = collection.Remove().clone();

因此,在创建新集合时,您将从原始集合中删除元素。你不想这样做...

鉴于您的 CollectionInterface 具有 Add,目前还不清楚如何实现您想要的目标删除方法(应该是addremove以遵循Java命名约定)来处理元素 - 无法非破坏性地访问集合。对于集合类型来说,这非常很奇怪。您首先这样做而不是使用内置集合有什么原因吗?

编辑:啊 - 我刚刚有一个想法。 类中,您可以访问正在构建的集合的内部...因此您可以通过调用从给定的集合中破坏性地复制元素 删除(就像现在一样),但是当您构建数组后,您可以使用:

for (int i = 0; i < amountOfElements; i++)
{
collection.Add(elementArray[i].clone2());
}

...这将再次放回元素。但这可怕...

关于Java 奇怪的引用行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8174500/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com