Consider this
public class Data {
private final SomeField[] fields;
.....
public SomeField[] getFields() {
return map == null ? null : map.clone();
}
Security - Method returns internal array
Exposing internal arrays directly allows the user to modify some code that could be critical. It is safer to return a copy of the array.
I get that we should not use clone()
to copy objects, rather copy the objects using copy constructor
.
But that still copies the internal objects which are references.
What are recommended ways to avoid clone()
above?
Thanks
The utility method Arrays.copyOf(T[] original, int newLength) will create a new array with the same objects from the internal array.
The issue with return the internal array is usually about preventing unintended changes to the contents of the array, which would be shared any other clients. Sharing the contained objects is not usually of the same order of concern but if you are implementing some sort of map your requirements may be more stringent.
To solve this problem you must avoid to user ternary operator. Instead of this, you must use if operator.
Example:
public CustomMap[] getMap() { CustomMap[] obj = null;
}
OR
I solve my problem using the abouve code. I think that is mandatory to create a new object explicit. I think.
Regards!