gpt4 book ai didi

java - 如何制作数组的副本,并可以在公共(public)方法中返回该副本?

转载 作者:行者123 更新时间:2023-12-02 01:06:03 24 4
gpt4 key购买 nike

基本上我被告知,为了“ future ”的安全目的,我不应该让公共(public)方法返回数组。相反,它们应该是私有(private)的,如果我想返回一个数组,它必须是另一种方法中的某种副本。

这就是现在的样子..

public Object[] ownedObject() {

return objectArr;
}

如果我将其设为私有(private),则需要它的类将无法识别上面的方法。

事情是我需要在所述其他类和整个项目中使用该数组中的内容,因为我现在有 5 个不同的类,可以工作(返回的数组方法设置为公共(public)而不是私有(private))。

最佳答案

由于您担心此问题的安全方面,您可能需要 distinguish between shallow copy and deep copy of the array 。如果您的数组包含可变对象,您可能需要数组中每个元素的深拷贝,以确保状态不会从对象中泄漏。

假设您的数组类型为 MyTypea copy constructor :

public MyType[] ownedObject() {
MyType[] copyArr = new MyType[objectArr.lenght];
for (int i = 0; i < objectArr.lenght; i++) {
copyArr[i] = new MyType(objectArr[i]);
}
return copyArr;
}

还有其他方法to deep copy an object .

关于java - 如何制作数组的副本,并可以在公共(public)方法中返回该副本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60063276/

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