简体   繁体   中英

How do I make a copy of an Array, which I can return in a public method?

Basically I got told that I shouldn't have public methods returning Arrays for "future" security purposes. Instead they should be private, and if I wanna return an Array it would have to be some kind of copy in another method.

This is how it looks now..

public Object[] ownedObject() {

    return objectArr;
}

If I make this private the class that needs it doesn't recognize the method above.

Thing is I need to use the contents in that Array in said, other class, and the total project, as I have it right now with 5 different classes, works (with the returning Array-methods set to Public and not private).

As you are concerned with security aspect of this problem you might want to distinguish between shallow copy and deep copy of the array . If your array contains mutable objects you probably need a deep copy of every single element in the array to ensure that state is not leaking from your object.

Assuming that you array is of type MyType with a 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;
}

There are also other ways to deep copy an object .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM